用xml编写不保留格式? [英] Writing in xml does not keep the formatting?

查看:74
本文介绍了用xml编写不保留格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个字符串:

<test>I am a test</test>

但是当我将其写到xml文件中并打开它时,我有了这个:

But when I write it in my xml file, and open it, I have this :

&lt;test&gt;I am a test&lt;/test&gt;

我不知道如何使用良好的格式.我尝试使用HttpUtility.HtmlDecode,但不能解决我的问题.

I don't know how to use the good formatting. I tried HttpUtility.HtmlDecode, but it does not solve my problem.

您对此有想法吗?

很抱歉以前没有发布我的代码,我认为我的问题确实很琐碎.这是我刚刚写的示例,可以恢复这种情况(我不再工作,因此没有原始代码):

Edit : Sorry for not having posted my code before, I thought my problem was really really trivial. Here is a sample I just wrote that resumes the situation (I'm not at work anymore so I don't have the original code) :

XmlDocument xmlDoc = new XmlDocument();
doc.LoadXml("<root>" +
            "<test>I am a test</test>" +
            "</root>");
string content = xmlDoc.DocumentElement.FirstChild.InnerXml;

XDocument saveFile = new XDocument();
saveFile = new XDocument(new XElement("settings", content));
saveFile.Save("myFile.xml");

我只希望我的xml文件内容看起来像我的原始字符串,因此在我的情况下,文件通常包含:

I just want my xml file content looks like my original string, so in my case the file would normally contain :

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

对吗?但是,相反,我有类似的东西:

Right ? But instead, I have something like :

<settings>&lt;root&gt;&lt;test&gt;I am a test&lt;/test&gt;&lt;/root&gt;
</settings>

推荐答案

您可以按照

You can do something along the lines of Converting XDocument to XmlDocument and vice versa to convert the root element of your XmlDocument to an XElement and then add it to your XDocument:

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);
        }
    }        
}

然后使用如下:

        // Get legacy XmlDocument
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml("<root>" +
                    "<test>I am a test</test>" +
                    "</root>");

        // Add its root element to the XDocument
        XDocument saveFile = new XDocument(
            new XElement("settings", xmlDoc.ToXElement()));

        // Save
        Debug.WriteLine(saveFile.ToString());

输出为:

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

请注意,这避免了将 XmlDocument 转换为XML字符串并从头开始重新解析的开销.

Note this avoids the overhead of converting the XmlDocument to an XML string and re-parsing it from scratch.

这篇关于用xml编写不保留格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆