XmlReader problem with &

A

Amit

I have assigned a simple xml into a XmlReader. A switch case loops
through the nodes and writes the data to XmlWriter object which is
initialized to a xml file. The output xml file is correctly generated
and everything works fine. But if the input xml has an & then I am
unable to generate a valid output xml file.

I have pasted the code below:

public class Class1
{
public Class1()
{
}
public static void Main(string[] args)
{
StringBuilder sb = new StringBuilder(@"<FName>First &amp;
Name</FName>");
System.IO.StringReader sr = new
System.IO.StringReader(sb.ToString());
System.Xml.XmlTextReader xtr = new
System.Xml.XmlTextReader(sr);
System.Xml.XmlReader xr = xtr;
System.Xml.XmlTextWriter xtw = new
System.Xml.XmlTextWriter("Output.xml", new System.Text.UTF8Encoding());
System.Xml.XmlWriter xw = xtw;

while (xr.Read())
{
switch (xr.NodeType)
{
case System.Xml.XmlNodeType.Element:
xw.WriteStartElement(xr.LocalName);
break;
case System.Xml.XmlNodeType.EndElement:
xw.WriteEndElement();
break;
case System.Xml.XmlNodeType.Text:
xw.WriteRaw(xr.Value);
break;
default: break;
}
}
xr.Close();
xw.Flush();
xw.Close();
}
}

Please help.

Thanks,
Amit
 
J

Jon Skeet [C# MVP]

Amit said:
I have assigned a simple xml into a XmlReader. A switch case loops
through the nodes and writes the data to XmlWriter object which is
initialized to a xml file. The output xml file is correctly generated
and everything works fine. But if the input xml has an &amp; then I am
unable to generate a valid output xml file.

When you read the value, the &amp; is translated into &. You're then
calling WriteRaw, which is writing out the & as-is - resulting in an
invalid XML file.

If you change the call to WriteRaw to WriteString, it will work fine.

Jon
 
A

Amit

Thanks .. ...Now it's fine

When you read the value, the &amp; is translated into &. You're then
calling WriteRaw, which is writing out the & as-is - resulting in an
invalid XML file.

If you change the call to WriteRaw to WriteString, it will work fine.

Jon
 

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

Top