Indenting XML output?

D

David Veeneman

I'm having a problem getting XML output properly formatted. specifically,
line breaks and indentation are missing, even though I'm using an
XmlTextWriter with Formatting = Formatting.Indented.

Here is the code that's generating the problem:

static void Main(string[] args)
{
// Create an XML document
XmlDocument document = new XmlDocument();

// Add an XML declaration section
XmlNode newNode = document.CreateNode(XmlNodeType.XmlDeclaration,"","");
document.AppendChild(newNode);

// Add a root element
XmlElement newElement = document.CreateElement("DemoXmlDocument");
XmlText newElementText = document.CreateTextNode("This is the text of
the root element");
newElement.AppendChild(newElementText);
document.AppendChild(newElement);

// Get the root element
XmlElement rootElement = document.DocumentElement;

// Add a child element
newElement = document.CreateElement("SampleElement");
newElementText = document.CreateTextNode("The text of the sample
element");
newElement.AppendChild(newElementText);
rootElement.AppendChild(newElement);

// Save the XML document to file
string fileName = @"c:\temp\DemoDocument.xml";
XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.Default);
writer.Formatting = Formatting.Indented;
document.Save(writer);
writer.Close();
}

Here's what the output from the program looks like:

<?xml version="1.0"?>
<DemoXmlDocument>This is the text of the root element<SampleElement>The text
of the sample element</SampleElement></DemoXmlDocument>

The content is fine, but the formatting is a mess. Any ideas why? Thanks for
your help.
 
D

David Veeneman

I found my answer. The XML formatter was being thrown off by the fact that I
had included a text attribute in my root element. So, I changed my root
element to the following:

// Add a root element
XmlElement newElement = document.CreateElement("DemoXmlDocument");
document.AppendChild(newElement);

The document now formats correctly.
 
C

csharp

This will work aswell... using the XmlTextWriter.Formatting =
Formatting.Indented.
Maybe easier
public static void WriteIndentedXml(string xml)
{
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(xml);
}
catch (Exception ex)
{
Assert.Fail(ex.ToString());
}

System.IO.StringWriter stringWriter = new System.IO.StringWriter();
XmlTextWriter writer = new XmlTextWriter(stringWriter);
writer.Formatting = Formatting.Indented;
doc.WriteTo(writer);
writer.Flush();

Console.WriteLine(stringWriter.ToString());
}
 
D

David Veeneman

I did find an answer to this--the problen was that I was adding element text
to the root element, which was confusing the XML formatter. Elements that
are designed to contain other elements shouldn't get element text.
 

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