【问题标题】:C# Xml EncodingC# Xml 编码
【发布时间】:2016-07-13 09:25:15
【问题描述】:

我现在正被 C# 和 XmlDocuments 吓坏了。

我需要将 XML 数据解析为另一个 XML,但我无法使用特殊字符。

我正在使用 XmlDocument 和 XmlNode。

到目前为止我尝试了什么:
- XmlDocument.CreateXmlDeclaration("1.0", "UTF-8", "yes");
- XmlTextWriter writer = new XmlTextWriter(outputDir + "systems.xml", Encoding.UTF8);

我确定的:
- 输入的 XML 也是 UTF-8
- “InnerText”值被编码而不替换字符

这里有一些代码(不是所有的......很多代码):

XmlDocument newXml = new XmlDocument();
newXml = (XmlDocument)systemsTemplate.Clone();
newXml.CreateXmlDeclaration("1.0", "UTF-8", "yes");
newXml.SelectSingleNode("systems").RemoveAll();
foreach(XmlNode categories in       exSystems.SelectNodes("root/Content/Systems/SystemLine"))
        {
            XmlNode categorieSystemNode = systemsTemplate.SelectSingleNode("systems/system").Clone();
            categorieSystemNode.RemoveAll();
            XmlNode importIdNode = systemsTemplate.SelectSingleNode("systems/system/import_id").Clone();
            string import_id = categories.Attributes["nodeName"].Value;
            importIdNode.InnerText = import_id;
            categorieSystemNode.AppendChild(importIdNode);
            [way more Nodes which I proceed like this]
        } 
 newXml.SelectSingleNode("systems").AppendChild(newXml.ImportNode(categorieSystemNode, true));
XmlTextWriter writer = new XmlTextWriter(outputDir + "systems.xml", Encoding.UTF8);
        writer.Formatting = Formatting.Indented;
        newXml.Save(writer);
        writer.Flush();
        writer.Close();

但我得到的是这个例子:

<intro>&lt;p&gt;Whether your project [...]</intro>

而不是这个:

<intro><p>Whether your project [...] </p></intro>

我在 XML 中有其他非 html 标签,所以请不要提供 HTML 解析解决方案:/
我知道我可以用 String.Replace() 替换字符,但这很脏而且不安全(而且速度很慢,大约 20K 行)。

我希望有一种更简单的方法可以做到这一点。

亲切的问候,
埃里瓦斯

【问题讨论】:

  • 请提供minimal reproducible example。您的代码包含许多不相关的内容,并且不清楚问题出在哪里。作为一个可能的提示,如果您将InnerText 设置为 XML 内容,您将遇到此问题,这与文本编码无关。如果您想要一种“更简单的方式”,我强烈建议您放弃XmlDocument LINQ to XML。
  • 你试过InnerXml而不是InnerText吗?

标签: c# xml encoding xmldocument xmlnode


【解决方案1】:

XmlDocument 的主要建议是提供一种简单的方法来处理 XML 文档,同时确保结果是格式良好的文档。

因此,在您的示例中使用InnerText,您让框架对字符串进行编码并将其正确插入到该文档中。每当您读取相同的值时,它将被解码并与原始字符串完全一样返回给您。

但是,如果您仍然想添加 XML 片段,您应该坚持使用 InnerXml 或 ImportNode。您必须意识到这可能会导致文档结构更加复杂,并且您可能希望避免这种情况。

作为第三种可能性,您可以使用CreateCDataSection 添加CDATA 并在那里添加您的文本。

您绝对应该通过尝试Replace 来避免将该 XML 文档视为字符串;坚持框架,你会没事的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-04
    • 2011-03-04
    • 2011-10-21
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    相关资源
    最近更新 更多