views:

317

answers:

5

I have a string that has angle brackets in it like this:

<element1>my text here</element1>

The string literally looks like this when I write it to console or my dataGridView or anywhere else. However, I'm trying to write this as part of an XML document.

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

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

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

Thanks!

-Adeena

A: 

That is being written as HTML Encoded Format as your application must think that it is content rather than actual XML elements so it is escaping it as if it were content.

Have you tried using the XmlWriter Class?

Turnkey
+2  A: 

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

<xml><![CDATA[<element1>my text here</element1>]]></xml>
Ant P.
A: 

Hmm.

So I think I've decided that instead of using the XMLSerializer (which I thought would be the fancy way of doing things) I'm just going to build up strings of all my elements and write them out as a normal text file. That's seeming to work and be straightforward enough. I had a couple other unique/odd things and this way of doing it makes it all that much simpler. :)

-Adeena

adeena
Bad idea, for the reasons explained byme.yahoo.com/a/Tad.Kk
bortzmeyer
+2  A: 

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

If you output it like the following, then the XML parser is going to interpret "<element1>" as part of the structure, and not as content.

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

As for writing your XML as strings, this is a bad idea: the escaping is there for a reason, and unless you know the XML spec in great detail, you are all but guaranteed to make a mistake doing it.

kdgregory
+1  A: 

The string literally looks like this when I write it to console or my dataGridView or anywhere else.

You should never manipulate the string value of an XML document directly.

I don't make a lot of absolute statements about software development, but that one's almost invariably true. It's definitely true if you're not deeply experienced with XML. I'd guess that 25% or more of the problems that people new to XML have with it are caused by this.

The string will appear properly if you load the XML into an XmlDocument, find the element that contains it, and write out the element's InnerText property. The DOM properly round-trips text into and out of XML, encoding it so that markup in the text doesn't interfere with the markup of the XML. You want that.

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

Robert Rossney