How to replace attribute's special characters using XMLTextReader

G

Goran Djuranovic

Hi all,
I ran into a problem where my XMLTextReader fails on .Read() when I have "<" character in one of the attribute's values. What I am trying to do is replace illegal characters ("<", "&" , etc.) with legal stuff ("&lt;", "&amp;", etc.), before I send the XML text to a SQL Server stored procedure. Currently, I am using XMLTextReader and StringWriter to do this, here is the piece of code that fails:
----------------------------------------------------------
With .XMLTextReaderObj
Do While (.Read() = True)
Select Case .NodeType
Case XmlNodeType.Element
Me.XMLStringWriterObj.Write("<" & .Name)
If .IsEmptyElement = True Then
EndTagStr = "></" & .Name & ">"
If .HasAttributes = True Then
While .MoveToNextAttribute()
Me.XMLStringWriterObj.Write(" {0}='{1}'", .Name, Replace(Replace(Replace(Replace(Replace(.Value, Chr(38), "&amp;"), Chr(60), "&lt;"), Chr
(62), "&gt;"), Chr(34), "&quot;"), Chr(39), "&apos;"))
End While
End If
Else
EndTagStr = ">"
If .HasAttributes = True Then
While .MoveToNextAttribute()
Me.XMLStringWriterObj.Write(" {0}='{1}'", .Name, Replace(Replace(Replace(Replace(Replace(.Value, Chr(38), "&amp;"), Chr(60), "&lt;"), Chr
(62), "&gt;"), Chr(34), "&quot;"), Chr(39), "&apos;"))
End While
End If
End If
Me.XMLStringWriterObj.Write(EndTagStr)
Case XmlNodeType.Text
Me.XMLStringWriterObj.Write(Replace(Replace(Replace(Replace(Replace(.Value, Chr(38), "&amp;"), Chr(60), "&lt;"), Chr(62), "&gt;"), Chr(34), "&quot;"),
Chr(39), "&apos;"))
Case XmlNodeType.EndElement
Me.XMLStringWriterObj.Write("</" & .Name & ">")
End Select
Loop
.Close()
End With

Any suggestions appreciated
Thanks
Goran
 
G

Goran Djuranovic

Hi,
I am already doing that, but the problem is that it fails before I can even change "<" it to "&lt;". It fails on .Read().

It looks like the XMLTextReader cannot even go forward if it finds "<", therefore making it impossible to change "<" to "&lt;".

Any other suggestions?
Thanks
Goran
Just use the char codes like you are doing without the &amp; etc

Newbie Coder
 
G

Goran Djuranovic

More information available in "dotnet.xml" thread, so consider this one closed.

Goran Djuranovic

Hi,
I am already doing that, but the problem is that it fails before I can even change "<" it to "&lt;". It fails on .Read().

It looks like the XMLTextReader cannot even go forward if it finds "<", therefore making it impossible to change "<" to "&lt;".

Any other suggestions?
Thanks
Goran
Just use the char codes like you are doing without the &amp; etc

Newbie Coder
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top