Formatted Xml

  • Thread starter Thread starter JSheble
  • Start date Start date
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!
 
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.
 
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.
 
Back
Top