Share via


Align Attributes when Formatting XML using LINQ to XML

Sometimes an XML element contains a large number of attributes, and the values of the attributes may be long.  When written to the console, such lines wrap, making it hard to read the XML.  In particular, the XML responses from SharePoint web services often contain many attributes for each element.  However, you can use appropriate settings for an XmlWriter so that the attributes are aligned, and each attribute is on a separate line.  This post shows how to do this.

This blog is inactive.
New blog: EricWhite.com/blog

Blog TOC

XNamespace w = "https://www.northwind.com/examples/2008";
XElement root = new XElement(w + "Root",
new XAttribute(XNamespace.Xmlns + "w", w.NamespaceName),
new XAttribute("RootAtt1", 1),
new XAttribute("RootAtt2", "This is an attribute with a very long value"),
new XAttribute("RootAtt3", 3),
new XElement(w + "Child",
new XAttribute(w + "Att1", 1),
new XAttribute("Att2", 2)
)
);
Console.WriteLine(root);

When this example is run, the console window will look like this:

<w:Root xmlns:w="https://www.northwind.com/examples/2008" RootAtt1="1" RootAtt2="
This is an attribute with a very long value" RootAtt3="3">
<w:Child w:Att1="1" Att2="2" />
</w:Root>

The following example shows how to use XmlWriter to align attributes:

XNamespace w = "https://www.northwind.com/examples/2008";
XElement root = new XElement(w + "Root",
new XAttribute(XNamespace.Xmlns + "w", w.NamespaceName),
new XAttribute("RootAtt1", 1),
new XAttribute("RootAtt2", "This is an attribute with a very long value"),
new XAttribute("RootAtt3", 3),
new XElement(w + "Child",
new XAttribute(w + "Att1", 1),
new XAttribute("Att2", 2)
)
);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
settings.NewLineOnAttributes = true;
using (XmlWriter xmlWriter = XmlWriter.Create(Console.Out, settings))
root.WriteTo(xmlWriter);

This produces the following output:

<w:Root xmlns:w="https://www.northwind.com/examples/2008"
RootAtt1="1"
RootAtt2="This is an attribute with a very long value"
RootAtt3="3">
<w:Child
w:Att1="1"
Att2="2" />
</w:Root>

This is much easier to read if there are many attributes.