xmltextwriter

  • Thread starter Thread starter quest
  • Start date Start date
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.
 
"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/
 
Use writer.WriteRaw() instead of WriteString() which will not escape
the special characters.

-Thagna
 
Back
Top