Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Built in .NET function for unescaping characters in XML stream?

Tags:

c#

.net

xml

So, I have some data in the form of:

<foo><bar>test</bar></foo>

What .NET classes/functions would I want to use to convert this to something pretty and write it out to a file looking something like this:

<foo>
   <bar>
       test
   </bar>
</foo>

Be specific on the functions and classes please, not just "use System.XML". There seems to be a lot of different ways to do things in .NET using XML :(

Thanks

like image 494
Polaris878 Avatar asked Feb 04 '10 21:02

Polaris878


People also ask

Why do we need to escape certain characters in XML?

With as popular as XML is, when creating XML files you need to be able to escape certain characters that will not parse correctly if they are not escaped. Until recently I always did this like most other .Net programmers, I wrote a function to do it.

What are XML metacharacters?

These special characters are also referred to as XML Metacharacters. By the process of escaping, we would be replacing these characters with alternate strings to give the literal result of special characters.

Why unescaping first in a string?

The reason for unescaping first is the content we were receiving contained unescaped as well as escaped special characters in the same XML element value, and we just hacked our way around using the said sequence of String.Replace commands to prevent use of more complex regex patterns.

Is the character '&' legal in XML?

If you don't mind 3rd party code and want to ensure no illegal characters make it into your XML, I would recommend Michael Kropat's answer. & isn't valid XML.


1 Answers

Using the System.Xml.XmlDocument class...

Dim Val As String = "&lt;foo&gt;&lt;bar&gt;test&lt;/bar&gt;&lt;/foo&gt;"
Dim Xml As String = HttpUtility.HtmlDecode(Val)

Dim Doc As New XmlDocument()
Doc.LoadXml(Xml)

Dim Writer As New StringWriter()
Doc.Save(Writer)

Console.Write(Writer.ToString())
like image 133
Josh Stodola Avatar answered Sep 20 '22 13:09

Josh Stodola