xmlwriter在一行中写入元素

kar*_*tal 6 c# xml xmlwriter

我尝试在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();
        }
Run Code Online (Sandbox Code Playgroud)

我发现记事本中的输出是这样的一行:

<?xml version="1.0" encoding="utf-8"?><cmap
xmlns:dcterms="http://purl.org/dc/terms/"><xmlns>http://cmap.ihmc.us/xml/cmap/</xmlns></cmap>
Run Code Online (Sandbox Code Playgroud)

我想它看起来像这样的多线:

<?xml version="1.0" encoding="utf-8"?> <cmap
xmlns:dcterms="http://purl.org/dc/terms/"><xmlns>http://cmap.ihmc.us/xml/cmap/</xmlns>
</cmap>
Run Code Online (Sandbox Code Playgroud)

ada*_*ost 12

您已经创建了XmlWriterSettings的实例.

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = "\t";
XmlWriter writer = XmlWriter.Create(savefilepath, settings);
Run Code Online (Sandbox Code Playgroud)

  • 值得一提的是,对于任何有这个问题的未来读者来说,写一个空格会阻止新的行/缩进工作.[XmlWriterSettings.Indent]的MSDN(http://msdn.microsoft.com/en-GB/library/system.xml.xmlwritersettings.indent.aspx) - "只要元素不包含混合内容,元素就会缩进一旦调用了WriteString或WriteWhitespace方法来写出混合元素内容,XmlWriter就会停止缩进.一旦混合内容元素关闭,缩进就会恢复." (6认同)