Office has a deeper integration with XML technology and developers are always looking for tips and tricks to work with XML documents. Office provides support to work with XML and you might be one of those developers that is programmatically generating Word documents (using WordprocessingML) , Excel spreadsheets (using SpreadsheetML), PowerPoint slides (using PresentationML), or Visio diagrams using (DataDiagrammingML). I think it always comes handy to have a list of tips and tricks to work with XML, and today I will share with you three simple ways of indenting an XML file/document.
Indenting XML files might sound as one of those netpick or nice-to-have enhancements that you don’t really need when you are working with XML. However, lots of applications and tools generate programmatically XML files and it always comes handy to open a nice and readable indented XML file instead of a “how can I edit this!” single line of eternal XML elements.
For managed applications:
- If you are generating XML files using and XmlTextWriter, you just need to do the following:
[VB.NET]
Dim writer as XmlTextWriter = new XmlTextWriter("data.xml",nothing)
writer.Formatting = Formatting.Indented
[C#]
XmlTextWriter writer = new XmlTextWriter("data.xml",null);
writer.Formatting = Formatting.Indented;
- If you are generating XML files/documents using DOM (XmlDocument) , you can add an XmlTextWriter to indent the code and you will be done:
[VB.NET]
Dim doc as XmlDocument = new XmlDocument()
' Save the document to a file and auto-indent the output.
Dim writer as XmlTextWriter = new XmlTextWriter("data.xml",nothing)
writer.Formatting = Formatting.Indented
doc.Save(writer)
[C#]
XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
// Save the document to a file and auto-indent the output.
XmlTextWriter writer = new XmlTextWriter("data.xml",null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);
For any platform:
- If you are generating XML files using an XSL transform file, you just need to add a simple line to your XSL file.
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="no" indent="yes" encoding="US-ASCII"/>
Happy Office XML programming!
Yes, very nice Tip.
Hi Imi!
It’s always nice to see your comments :).
I was reading today an internal distribution list and I saw an interesting thread about autonumbered…
For some reason the indentation formatting won’t work for me. I have an XML file called GGData that I want to format. I have the following lines of code:
Dim doc As New XmlDocument()
Dim writer As New XmlTextWriter("GGData.xml", Nothing)
writer.Formatting = Formatting.Indented
doc.Save(writer)
The above overwrites my GGData.xml file with a blank file of 0 bytes.
Hi Erika
Have you ever done the above indenting on the output of SQL Server "for xml"?
cheers
/s
fshost, you first have to load the original document into the XmlDocument instance. So put a "doc.Load("GGData.xml")" line between the "new XmlDocument()" and "Dim writer As ", and it should work…
Do you have any tips related to simplifying WordML(2003) documents?
The back story: I receive documents to be converted to pdf from the legal department in Word format (2003) and when I save the documents as pdfs the documents are often very disjointed I think because legal is tracking all the changes in the documents and to adequately track the changes it creates many nodes. Can these documents be re-combined to be simplified again?
i want to fetch from Text File in connectivity from VB.NET into XML.
Text File must be UNICODE
IF U have any code for related to it’s topic plz sent me
my email-id :
http://www.chaudhary_aparna20@yahoo.co.in
plz send meeeeeeeeeeeeeeeeee
How abt for display in a TextBox?
i tried XmlDataDocument.InnerXml but all XML in 1 line…
If you want it in a TextBox I assume you’d need to put the formated xml in a string. Here’s how I did it.
public static string FormatXml(XmlDocument doc) {
XmlTextWriter xmlWriter;
StringWriter textWriter;
// Format the Xml document with indentation and save it to a string.
textWriter = new StringWriter();
xmlWriter = new XmlTextWriter(textWriter);
xmlWriter.Formatting = Formatting.Indented;
doc.Save(xmlWriter);
return textWriter.ToString();
}
Works perfect. Thank you for this simple but accurate snippet!
Thanks for the indent code. It worked very well.
And for using tab as indentation char, additionally set:
l_XMLWriter.IndentChar = ‘t’;
l_XMLWriter.Indentation = 1;
before
l_XMLDoc.Save(l_XMLWriter);
<p>The following is an example of extracting correctly indented XML from an Xml document…</p> …
the .IndentChar and .Indentation properties seem only to work when you are writing it line by line, if however you do something along the lines of:
doc.Load("C:data.xml")
Dim writer As New XmlTextWriter("C:data.xml", Nothing)
writer.Formatting = Formatting.Indented
writer.IndentChar = Chr(9) ‘ =’t’
writer.Indentation = 3
doc.Save("C:data_indented.xml")
the xml is indented, but not to the level specified, and reordering the property assignemtn doesn’t seem to solve the problem… has anyone else tried this?
xmlindenter: I’m having exactly the same problem, and i haven’t yet figured it out.
It would be nice if someone could guide us.
Thanks msdn@chasmer.com
Yours is the best on the internet 🙂
Can anybody tell me what is the name of the file to change this?
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="no" indent="yes" encoding="US-ASCII"/>
Thanks – this piece was REALLY USEFULL!!
XmlTextWriter writer = new XmlTextWriter("data.xml",null);
writer.Formatting = Formatting.Indented;
Like Sexton said:
Have you ever done the above indenting on the output of SQL Server "for xml"?
Make sure you close the XmlTextWriter after you’re done with it otherwise you’ll leave file handles open!!
writer.Close();
There are problems in .NET’s implementation. For instance, if you modify a node by assigning its InnerXml and then save the XML immediately, it will retain the indenting (if any) in the string you assigned to InnerXml, no matter how you set PreserveWhiteSpace or Formatting or whatever. If you work on the XmlDocument later, inserting, modifying nodes, the indenting will return to normal but not if you save immediately.
private static string FormatXml(XmlDocument doc)
{
string rtn = string.Empty;
using (StringWriter textWriter = new StringWriter())
{
using (XmlTextWriter xmlWriter = new XmlTextWriter(textWriter))
{
xmlWriter.Formatting = Formatting.Indented;
doc.Save(xmlWriter);
}
rtn =textWriter.ToString();
}
return rtn;
}
Ironic that the article is about formatting markup and the comments strip out all indentation.
private static string IndentXMLString(String xml)
{
try
{
// Cargo el XML sin formato
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xml);
// Configuro el formato
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = "t";
settings.OmitXmlDeclaration = true;
settings.NewLineOnAttributes = false;
// Formateo y retorno
StringBuilder output = new StringBuilder();
XmlWriter writer = XmlWriter.Create(output, settings);
xmldoc.WriteContentTo(writer);
writer.Flush();
return output.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return "";
}
If you want to indent online : http://www.indentation-xml.com