XMLWriter如何在一行中写入元素

6

我尝试将应用程序中的一些元素保存在xml文件中,但是当我使用以下代码进行开发时:

public static void WriteInFile(string savefilepath)
        {
            XmlWriter writer = XmlWriter.Create(savefilepath);
            WriteXMLFile(writer);

        }
private static void WriteXMLFile(XmlWriter writer) //Write and Create XML profile for specific type 
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("cmap");
            writer.WriteAttributeString("xmlns", "dcterms",null, "http://purl.org/dc/terms/");
            writer.WriteElementString("xmlns", "http://cmap.ihmc.us/xml/cmap/");
           // writer.WriteAttributeString("xmlns","dc",null, "http://purl.org/dc/elements/1.1/");
            //writer.WriteAttributeString("xmlns", "vcard", null, "http://www.w3.org/2001/vcard-rdf/3.0#");
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Close();
        }

我发现在记事本中输出的内容都在一行,就像这样:

<?xml version="1.0" encoding="utf-8"?><cmap
xmlns:dcterms="http://purl.org/dc/terms/"><xmlns>http://cmap.ihmc.us/xml/cmap/</xmlns></cmap>

我希望它可以像这样多行显示:

<?xml version="1.0" encoding="utf-8"?> <cmap
xmlns:dcterms="http://purl.org/dc/terms/"><xmlns>http://cmap.ihmc.us/xml/cmap/</xmlns>
</cmap>

你想要的输出完全相同。尝试在XMLEditor和/或Visual Studio中加载它。记事本并不以其格式选项而闻名。 - Security Hound
3个回答

14
你已经创建了一个XmlWriterSettings实例。
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = "\t";
XmlWriter writer = XmlWriter.Create(savefilepath, settings);

6
值得一提,对于任何遇到此问题的未来读者,写入空格会阻止换行/缩进起作用。XmlWriterSettings.Indent 的MSDN文档中描述:"只要元素不包含混合内容,就会缩进元素。一旦调用WriteString或WriteWhitespace方法以写出混合元素内容,则XmlWriter停止缩进。在混合内容元素关闭后,缩进恢复。" - Kobunite

4
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (var writer = XmlWriter.Create(savefilepath, settings))
{
     WriteXMLFile(writer);
}

2

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