【发布时间】:2014-06-06 12:36:29
【问题描述】:
我有一些代码来替换 XML 文档的根节点名称,同时保留其名称空间。
XmlDocument doc = new XmlDocument();
Stream inStream = inmsg.BodyPart.GetOriginalDataStream();
doc.Load(inStream);
XmlNode root = doc.DocumentElement;
XmlNode replacement = doc.SelectSingleNode("/*/*[1]");
XmlNode newRoot = doc.CreateElement(replacement.Name);
XmlAttribute xmlns = (XmlAttribute)root.Attributes["xmlns"].Clone();
newRoot.Attributes.Append(xmlns);
newRoot.InnerXml = root.InnerXml; //the problem is here!
doc.ReplaceChild(newRoot, root);
以这样开头的文档:
<OLD_ROOT xmlns="http://my.xml.namespace">
<NEW_ROOT>
结果:
<NEW_ROOT xmlns="http://my.xml.namespace">
<NEW_ROOT xmlns="http://my.xml.namespace">
第二个xmlns 是因为InnerXml 属性显然将它设置在其内容的第一个节点上!我可以做些什么来规避这种情况,而不必事后将其删除?
之后无法删除:
用下面的代码试过
XmlNode first_node = doc.SelectSingleNode("/*/*[1]");
XmlAttribute excess_xmlns = first_node.Attributes["xmlns"];
first_node.Attributes.Remove(excess_xmlns);
但这不起作用,因为xmlns 显然不作为该节点上的属性存在!
【问题讨论】:
-
何必呢?它看起来多余但无害。有了 XDocument,这一切都变得容易多了。
-
@HenkHolterman,嗯。请详细说明 XDocument?
-
doc.Root.Name = replacement.Name; -
@HenkHolterman 哇,我从来不知道会这么容易。很惊讶我自己没有找到这个,因为我做了很多研究。谢谢!
-
我没有测试这是否可以解决您的问题,并且从其他 cmets/answers 看起来可能有更好的解决方案,但您可能无法访问命名空间声明属性,因为它位于命名空间本身 ("w3.org/2000/xmlns/")。
标签: c# .net xml xml-namespaces xmldocument