在XML中编写不会保留格式吗?

25 浏览
0 Comments

在XML中编写不会保留格式吗?

我有这个字符串:\n

I am a test

\n但是当我将它写入我的xml文件并打开它时,我得到了这个:\n

<test>I am a test</test>

\n我不知道如何使用正确的格式。我尝试使用HttpUtility.HtmlDecode,但它没有解决我的问题。\n你对此有什么想法吗?\n编辑:抱歉之前没有发布我的代码,我以为我的问题非常非常琐碎。这是我刚刚编写的一个简单的示例,总结了情况(我现在不在工作,所以没有原始代码):\n

XmlDocument xmlDoc = new XmlDocument();
doc.LoadXml("" +
            "I am a test" +
            "");
string content = xmlDoc.DocumentElement.FirstChild.InnerXml;
XDocument saveFile = new XDocument();
saveFile = new XDocument(new XElement("settings", content));
saveFile.Save("myFile.xml");

\n我只想让我的xml文件内容看起来像我的原始字符串,\n所以在我的情况下,文件应该正常包含:\n


    
        I am a test
    

\n对吗?但是相反,我得到了这样的结果:\n

<root><test>I am a test</test></root>

0
0 Comments

在使用XML进行编写时,可能会遇到格式丢失的问题。解决方法是将XmlDocument的根元素转换为XElement,然后添加到XDocument中。具体操作如下:

首先,创建一个XmlDocumentExtensions的扩展类,实现将XmlDocument转换为XElement的方法。

public static class XmlDocumentExtensions
{
    public static XElement ToXElement(this XmlDocument xmlDocument)
    {
        if (xmlDocument == null)
            throw new ArgumentNullException("xmlDocument");
        if (xmlDocument.DocumentElement == null)
            return null;
        using (var nodeReader = new XmlNodeReader(xmlDocument.DocumentElement))
        {
            return XElement.Load(nodeReader);
        }
    }        
}

然后,使用以下代码将根元素添加到XDocument中:

// 获取旧的XmlDocument
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("<root>" +
            "<test>I am a test</test>" +
            "</root>");
// 将根元素添加到XDocument中
XDocument saveFile = new XDocument(
    new XElement("settings", xmlDoc.ToXElement()));
// 保存
Debug.WriteLine(saveFile.ToString());

运行以上代码,可以得到如下输出:

<settings>
  <root>
    <test>I am a test</test>
  </root>
</settings>

这样就避免了将XmlDocument转换为XML字符串后重新解析的开销。

以上就是解决XML编写时格式丢失的问题的方法。

0