Writing formatted XML with XmlWriter

None picture None · Sep 23, 2011 · Viewed 16.8k times · Source

I'm trying to write to an XML file to the isolated storage but I would like to format it like this:-

<SampleData>
  <Item Property1="AliquaXX" />
  <Item Property1="Integer" />
  <Item Property1="Quisque" />
  <Item Property1="Aenean" />
  <Item Property1="Mauris" />
  <Item Property1="Vivamus" />
  <Item Property1="Nullam" />
  <Item Property1="Nam" />
  <Item Property1="Sed" />
  <Item Property1="Class" />
</SampleData>

but I'm buggered if I can work it out, can anyone help?

Answer

Jon Skeet picture Jon Skeet · Sep 23, 2011

I suspect you need to create an XmlWriterSettings with the behaviour you want (indentation etc) and then pass that to the XmlWriter on creation. Just setting Indent to true may well be enough:

XmlWriterSettings settings = new XmlWriterSettings { Indent = true };
using (XmlWriter writer = XmlWriter.Create(..., settings))
{
    ...
}