xmlwriter在一行中写入元素

时间:2011-12-15 14:00:39

标签: 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();
        }

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

<?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>

3 个答案:

答案 0 :(得分:12)

您已创建XmlWriterSettings.

的实例
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = "\t";
XmlWriter writer = XmlWriter.Create(savefilepath, settings);

答案 1 :(得分:3)

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

答案 2 :(得分:2)

您应该使用XmlWriterSettings - 设置适当的格式选项并在创建XmlWriter时传递它。

在此处详细了解:http://msdn.microsoft.com/en-us/library/kbef2xz3.aspx