user1561275
user1561275

Reputation: 71

Save string to XML File

I want to save the following string in an XML File:

<text><![CDATA[<p>what is my pet name</p>]]></text>

When I am saving it, it looks like:

<text>&lt;![CDATA[&lt;p&gt;what is my pet name&lt;/p&gt;]]&gt;</text>

I have tried File.WriteAllText(), XmlDocument.Save() methods but didnt get the proper response.

basically everywhere other than opening and closing tags in the XML, < is replaced by &lt; and > is replaced by &gt;.

Upvotes: 1

Views: 3015

Answers (3)

Wesley
Wesley

Reputation: 5621

XML is being written correctly.

XML has special characters that are reserved for commands, just like C# reserves words like "if" and "string".

XML is encoding your string for storage. What you need to do is when you retrieve your string, run it through a similar decode process.

Use this: HttpServerUtility.HtmlDecode(encodedString)

Reference: Decode XML returned by a webservice (< and > are replaced with &lt; and &gt)?

Upvotes: 0

What is happening is that the XML parser is encoding your string. When you try to access the string later, it can be decoded again at that time.

What I suggest, is that you either try to load the text as into a new 'XmlDocument' with XmlDocument.LoadXml(string s), and then import that into your current document, or leave it encoded.

You should not try to both use an XML parser, and manually add text at the same time.

Upvotes: 2

Sebastian
Sebastian

Reputation: 8005

I guess you add the CDATA manually and the XML writing mechanism correctly escapes your CDATA because it treats it as text content. Instead explicitly add a CDATA section with just the contents.

If you are using the old XML API (System.XML), then use this method to create the CDATA Section: http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.createcdatasection Then append the node to the element just like in the example in the link.

Upvotes: 1

Related Questions