How to write the contents of a string to XML without codes ...?

I have a line with angle brackets in it:

<element1>my text here</element1>

      

The string literally looks like this when I write it to the console or my dataGridView or wherever. However, I am trying to write this as part of an XML document.

Everything is fine, except that in the written xml file the above is displayed as:

&lt;element1&gt;my text here&lt;/element1&gt;

      

How do I get this to write as my literal text instead of codes?

Thank!

-Adeena

+1


source to share


5 answers


If you want to store it as a string without escaping all elements, use a CDATA block:



<xml><![CDATA[<element1>my text here</element1>]]></xml>

      

+4


source


Your goal is not clear to me: how do you want your final XML file to look like?

If you output it as shown below, then the XML parser will interpret "<element1>"; as part of the structure, not as content.



<container><element1>my text here</element1></container>

      

As far as writing your XML as a string, this is a bad idea: the escaping happens for some reason, and if you don't know the XML specification in great detail, you will almost certainly make a mistake.

+2


source


The string literally looks like this when I write it in the console or my dataGridView or wherever.

You shouldn't directly manipulate the string value of the XML document.

I don't make many absolute statements about software development, but this is almost always true. This is definitely true if you are not deep enough in XML. I guess 25% or more of the problems people with XML have to do with this.

The string will display correctly if you load the XML into the XmlDocument, find the element that contains it, and write down the element's InnerText property. The DOM correctly rounds and outputs text in XML by encoding it so that the markup in the text does not interfere with the XML markup. Do you want that.

Another thing I've observed is that at least 90% of the time, the suggestion to use CDATA is technically correct, but otherwise wrong. Using CDATA is a technique of last resort.

+2


source


This is written as HTML Encoded Format because your application must think it is content and not actual XML elements, so it eludes it as if it was happy with it.

Have you tried using the XmlWriter class?

0


source


Hmm.

So, I figured that instead of using the XMLSerializer (which I thought would be a fancy way of doing things), I'm going to create strings of all my elements and write them out as a plain text file. It seems to work and is simple enough. I had a couple of other unique / unusual things, and this way of doing it makes it all a lot easier. :)

-Adeena

-1


source







All Articles