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

时间:2010-11-04 05:45:27

标签: c# xml xmlwriter

我正在将一些数据写入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 个答案:

答案 0 :(得分:40)

使用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
}

答案 1 :(得分:27)

您需要先创建一个指定缩进的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();
  }
}

答案 2 :(得分:7)

检查“设置”属性:

w.Settings.Indent = true;

编辑:您无法直接设置:

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

答案 3 :(得分:3)

设置XmlTextWriter的格式化属性:

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

答案 4 :(得分:1)

使用设置如下:

        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,重要的部分就是设置。

答案 5 :(得分: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

检查doco是否有其他设置和文件覆盖选项,但这很干净,在很多情况下都可以正常工作。