Formatted Xml

J

JSheble

I have a method in my class that needs to return formatted XML, with the
carriage returns, linefeeds, and tabs... However, when I return
oXml.OuterXml, the Xml is not formatted...

Every example I've seen involves writing the Xml to disk before it's
formatted (or perhaps is formatted while it's being written) which doesn't
help me at all...

So how can I return a formatted Xml string from the XmlDocument object?

Thanx!
 
M

Martin Honnen

JSheble said:
So how can I return a formatted Xml string from the XmlDocument object?

You can use the WriteTo method to write to an XmlTextWriter over a
StringWriter where you set the XmlTextWriter to format as you need it e.g.

XmlDocument xmlDocument = new XmlDocument();
XmlElement gods = xmlDocument.CreateElement("gods");
XmlElement god = xmlDocument.CreateElement("god");
god.AppendChild(xmlDocument.CreateTextNode("Kibo"));
gods.AppendChild(god);
xmlDocument.AppendChild(gods);

StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
xmlWriter.Formatting = Formatting.Indented;

xmlDocument.WriteTo(xmlWriter);
xmlWriter.Flush();
xmlWriter.Close();

string formattedXML = stringWriter.ToString();

Console.WriteLine("Formatted XML:\r\n{0}", formattedXML);

gives

<gods>
<god>Kibo</god>
</gods>


You could also use the Save method to Save to a MemoryStream or to an
XmlTextWriter over a StringWriter or a StringWriter itself.
 
J

JSheble

Thanx... that was exactly what I needed...

You can use the WriteTo method to write to an XmlTextWriter over a
StringWriter where you set the XmlTextWriter to format as you need it
e.g.

XmlDocument xmlDocument = new XmlDocument();
XmlElement gods = xmlDocument.CreateElement("gods");
XmlElement god = xmlDocument.CreateElement("god");
god.AppendChild(xmlDocument.CreateTextNode("Kibo"));
gods.AppendChild(god);
xmlDocument.AppendChild(gods);

StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
xmlWriter.Formatting = Formatting.Indented;

xmlDocument.WriteTo(xmlWriter);
xmlWriter.Flush();
xmlWriter.Close();

string formattedXML = stringWriter.ToString();

Console.WriteLine("Formatted XML:\r\n{0}", formattedXML);

gives

<gods>
<god>Kibo</god>
</gods>


You could also use the Save method to Save to a MemoryStream or to an
XmlTextWriter over a StringWriter or a StringWriter itself.
 

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