Writing formatted XML with XmlWriter

青春壹個敷衍的年華 提交于 2019-12-04 02:47:09

问题


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?


回答1:


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;



回答2:


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))
{
    ...
}



回答3:


If, like me, you're implementing your own XmlWriter you can do:

var myXmlWriter = new MyXmlWriter(stream, System.Text.Encoding.UTF8)
{
    Formatting = Formatting.Indented
};

or do this.Formatting = Formatting.Indented in it's constructor.




回答4:


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.



来源:https://stackoverflow.com/questions/7535280/writing-formatted-xml-with-xmlwriter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!