1

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;.

2
  • 2
    Please post the code that you are using to write to the file. Commented Aug 8, 2012 at 20:10
  • 1
    Please show the code that results in the above output. Commented Aug 8, 2012 at 20:11

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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)?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.