C#中XMLwriter的缩进和换行命令

36

我正在将一些数据写入XML文件......但当我打开它时,所有的值都在单行中......如何以可读格式编写它?也就是说,每个节点都在新行和缩进中?

FileStream fs = new FileStream("myfile.xml", FileMode.Create);

XmlWriter w = XmlWriter.Create(fs);

w.WriteStartDocument();
w.WriteStartElement("myfile");                 

w.WriteElementString("id", id.Text);
w.WriteElementString("date", dateTimePicker1.Text);
w.WriteElementString("version", ver.Text);
w.WriteEndElement();
w.WriteEndDocument();
w.Flush();
fs.Close();
6个回答

45
使用 XmlTextWriter 替代 XmlWriter,然后设置 Indentation 属性。

示例

string filename = "MyFile.xml";

using (FileStream fileStream = new FileStream(filename, FileMode.Create))
using (StreamWriter sw = new StreamWriter(fileStream))
using (XmlTextWriter xmlWriter = new XmlTextWriter(sw))
{
  xmlWriter.Formatting = Formatting.Indented;
  xmlWriter.Indentation = 4;

  // ... Write elements
}

根据@jumbo的评论,这也可以像.NET 2中那样实现。

var filename = "MyFile.xml";
var settings = new XmlWriterSettings() 
{
    Indent = true,
    IndentChars = "    "
}

using (var w = XmlWriter.Create(filename, settings))
{
    // ... Write elements
}

除非必要,否则您不能设置XmlSettings属性。 - Ed S.
4
使用XmlTextWriter已不再推荐(自.Net2.0以来)。有关更多信息,请查看此问答页面。 - jumbo

33
你需要先创建一个XmlWriterSettings对象来指定缩进,然后在创建XmlWriter时,在路径之后传入XmlWriterSettings。
此外,我使用“using”块来让C#处理资源的处理,以便我不必担心在异常情况下丢失任何资源。
{
  XmlWriterSettings xmlWriterSettings = new XmlWriterSettings()
  {
    Indent = true,
    IndentChars = "\t",
    NewLineOnAttributes = true
  };

  using (XmlWriter w= XmlWriter.Create("myfile.xml", xmlWriterSettings))
  {
    w.WriteStartDocument();
    w.WriteStartElement("myfile");

    w.WriteElementString("id", id.Text);
    w.WriteElementString("date", dateTimePicker1.Text);
    w.WriteElementString("version", ver.Text);
    w.WriteEndElement();
    w.WriteEndDocument();
  }
}

1
从技术上讲,将“Indent”设置为true就足以使Xml(Text?)Writer发出新行。 - Zack

8

检查设置属性:

w.Settings.Indent = true;

编辑:您无法直接设置它:

System.Xml.XmlWriter.Create("path", new System.Xml.XmlWriterSettings())

异常:'XmlWriterSettings.Indent' 属性是只读的,无法设置。 - Dark Knight
我的错,你需要使用“Create”方法并直接传递它;已更新答案。 - Jerod Venema

3

设置XmlTextWriter的格式属性:

TextWriter textWriter;
var xmlTextWriter = new XmlTextWriter(textWriter);
xmlTextWriter.Formatting = Formatting.Indented;

这个“Formatting”属性是在哪个.NET版本(或程序集)中的?我的解决方案针对4.5.1,但在Xml(Text?)Writer上没有任何“Formatting”属性。 - Zack
自 .net 2.0 起,XmlTextWriter 已被弃用。 - LarryBud

2
请按以下方式使用设置:
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Encoding = Encoding.UTF8;
        settings.Indent = true;

        using (MemoryStream memoryStream = new MemoryStream())
        using (XmlWriter xmlDoc = XmlWriter.Create(memoryStream, settings)){
         // logic here..
        }

这样做可以达到你想要的效果,但是你不必使用MemoryStream,重要的是设置。


0
一个使用XmlWriter和XmlWriterSettings直接写入文件的VB.NET小版本:
Dim oSerializer As New XmlSerializer(GetType(MyType), New XmlRootAttribute("MyRootAttributeName"))
Using oXmlWriter As XmlWriter = XmlWriter.Create("MyFilePath", New XmlWriterSettings With {.Indent = True}) //Default encoding is utf-8
    oSerializer.Serialize(oXmlWriter, oInstanceOfMyType)
    oXmlWriter.Flush()
End Using

请查看文档以获取其他设置和文件覆盖选项,但在许多情况下,此方法是清洁的并按预期工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接