Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing formatted XML with XmlWriter

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?

like image 455
None Avatar asked Sep 23 '11 21:09

None


People also ask

How to write XML using XmlWriter in c#?

using System. Xml; var sts = new XmlWriterSettings() { Indent = true, }; using XmlWriter writer = XmlWriter. Create("data. xml", sts); writer.

How do I format an XML file?

To access XML formatting options, choose Tools > Options > Text Editor > XML, and then choose Formatting.

What is XmlWriter?

The XmlWriter class writes XML data to a stream, file, text reader, or string. It supports the W3C Extensible Markup Language (XML) 1.0 (fourth edition) and Namespaces in XML 1.0 (third edition) recommendations.

How do you create an XmlWriter?

Creates a new XmlWriter instance using the stream and XmlWriterSettings object. Creates a new XmlWriter instance using the specified XmlWriter and XmlWriterSettings objects. Creates a new XmlWriter instance using the specified StringBuilder. Creates a new XmlWriter instance using the specified filename.


2 Answers

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))
{
    ...
}
like image 111
Jon Skeet Avatar answered Oct 28 '22 12:10

Jon Skeet


You can customize the xml output via the XmlWriterSettings.

You didn't include any code, but you can set the XmlWriterSettings when you create the XmlWriter. You can also just use something like:

var myXmlWriter = new XmlWriterSettings { Indent = true };
like image 31
Sam Avatar answered Oct 28 '22 10:10

Sam