xmltextwriter

Q

quest

XmlTextWriter writer = new XmlTextWriter("c:\\myxml.xml",
System.Text.Encoding.UTF8);
writer.WriteStartDocument(true);
writer.WriteStartElement("Heading");
writer.WriteAttributeString("Ver", "1-A");
writer.WriteString("<Test value=\"Hello\"/>");
writer.WriteEndElement();
writer.Close();

This line: writer.WriteString("<Test value=\"Hello\"/>"); produces a weird
output as following:

&lt;Test value="hello"/&gt;

where in actual fact it should give me :

<Test value="hello"/>

Any idea when this happened ? Thanks.
 
J

Jani Järvinen [MVP]

"Quest",
XmlTextWriter writer = new XmlTextWriter("c:\\myxml.xml",
System.Text.Encoding.UTF8);
...
writer.WriteString("<Test value=\"Hello\"/>");

This line: writer.WriteString("<Test value=\"Hello\"/>"); produces a weird
output as following:

&lt;Test value="hello"/&gt;

XmlTextWriter is operating correctly. You cannot output XML code directly
with the WriteString method -- you should use WriteRaw for this purpose.
What WriteString does is it writes out a set of characters, which are
where in actual fact it should give me :
<Test value="hello"/>

In this case, you should simply replace the problematic line with this piece
of code:

writer.WriteStartElement("Test");
writer.WriteAttributeString("value", "Hello");
writer.WriteEndElement();

But if you want to write XML code directly, you could use the aforementioned
WriteRaw method. However I don't generally recommend this method as you
should leave writing correct XML to the XmlTextWriter, and not bother about
it yourself.

Oh, it is good practice to put the XML generation code inside a try-finally
block, so that the "writer.Close();" call is inside the finally block.
Another alternative is to use the C# "using" statement.

--
Regards,

Mr. Jani Järvinen
C# MVP
Helsinki, Finland
(e-mail address removed)
http://www.saunalahti.fi/janij/
 
T

Thanga

Use writer.WriteRaw() instead of WriteString() which will not escape
the special characters.

-Thagna
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

trouble with xml writer 2
problem writing xml 3
XmlTextWriter & XmlTextReader 3
Problem Reading Xml file 9
XML Error help 1
combine a few xml files 4
Write to XML with C# 5
Textwriter 1

Top