Writing formatted XML with XmlWriter

2019-02-21 09:14发布

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?

Thanks, struggling newbie.

3条回答
倾城 Initia
2楼-- · 2019-02-21 09:28

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))
{
    ...
}
查看更多
Emotional °昔
3楼-- · 2019-02-21 09:38

You can use DataSet.GetXML()

Dim column As DataColumn
For Each column In DataSet.Tables.Item(0).Columns
    column.ColumnMapping = MappingType.Attribute
Next
Dim xml As String = DataSet.GetXml()

It is not related to XmlWriter but you can use it for formatting XML.

查看更多
做自己的国王
4楼-- · 2019-02-21 09:42

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:

myXmlWriter.Settings.Indent = true;
myXmlWriter.Settings.IndentChars = "     "; // note: default is two spaces
myXmlWriter.Settings.NewLineOnAttributes = false;
myXmlWriter.Settings.OmitXmlDeclaration = true;
查看更多
登录 后发表回答