【发布时间】: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><p>Whether your project [...]</intro>
而不是这个:
<intro><p>Whether your project [...] </p></intro>
我在 XML 中有其他非 html 标签,所以请不要提供 HTML 解析解决方案:/
我知道我可以用 String.Replace() 替换字符,但这很脏而且不安全(而且速度很慢,大约 20K 行)。
我希望有一种更简单的方法可以做到这一点。
亲切的问候,
埃里瓦斯
【问题讨论】:
-
请提供minimal reproducible example。您的代码包含许多不相关的内容,并且不清楚问题出在哪里。作为一个可能的提示,如果您将
InnerText设置为 XML 内容,您将遇到此问题,这与文本编码无关。如果您想要一种“更简单的方式”,我强烈建议您放弃XmlDocumentLINQ to XML。 -
你试过
InnerXml而不是InnerText吗?
标签: c# xml encoding xmldocument xmlnode