我在 Stackoverflow 中尝试了很多答案解决我的问题 this one .但似乎没有一个适用于我的 XML 文档。
这是我的 XML
<w:wordDocument xmlns:aml="http://schemas.microsoft.com/aml/2001/core" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:ve="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml" xmlns:wx="http://schemas.microsoft.com/office/word/2003/auxHint" xmlns:wsp="http://schemas.microsoft.com/office/word/2003/wordml/sp2" xmlns:sl="http://schemas.microsoft.com/schemaLibrary/2003/core"
w:macrosPresent="no"
w:embeddedObjPresent="no"
w:ocxPresent="no"
xml:space="preserve">
<w:ignoreSubtree
w:val="http://schemas.microsoft.com/office/word/2003/wordml/sp2" />
...
<w:body>
<w:p
wsp:rsidR="009D1011"
wsp:rsidRDefault="001D7CCD">
...
我正在寻找 <w:p>
具有命名空间的节点。
这是我最近的尝试:
string xmlNamespace = String.Empty;
XmlNamespaceManager nsmgr;
//xml is my XMLDocument
XmlNodeList nodeInfo = xml.GetElementsByTagName("w:wordDocument");
XmlAttributeCollection att = nodeInfo[0].Attributes;
xmlNamespace = Convert.ToString(nodeInfo[0].Attributes["xmlns"].Value);
nsmgr = new XmlNamespaceManager(xml.NameTable);
nsmgr.AddNamespace("w", xmlNamespace);
XmlNode myNode = xml.DocumentElement.SelectSingleNode("w:wordDocument/w:body", nsmgr);
但是myNode
总是返回 null
谁能告诉我我做错了什么?
最佳答案
您的代码存在问题:
- 要获取用于给定前缀(在本例中为
w
)的命名空间,您应该检查正确的xmlns:w
属性(不是默认的xmlns
,也不是像xmlns:alm
这样的随机文件,或者在大多数情况下只是明确指定 - 因为它永远不会在有效的 WordML 文档的情况下发生变化。 - 要选择从根开始的元素,您需要使用从根开始的 XPath 搜索 (
/w:....
) 或对以根元素作为子元素(文档本身)的节点执行选择).
工作代码的可能变体:
xmlNamespace = Convert.ToString(nodeInfo[0].Attributes["xmlns:w"].Value);
nsmgr = new XmlNamespaceManager(xml.NameTable);
nsmgr.AddNamespace("w", xmlNamespace);
XmlNode myNode = xml.SelectSingleNode("w:wordDocument/w:body", nsmgr);
或
nsmgr = new XmlNamespaceManager(xml.NameTable);
nsmgr.AddNamespace("w", "http://schemas.microsoft.com/office/word/2003/wordml");
XmlNode myNode = xml.DocumentElement
.SelectSingleNode("/w:wordDocument/w:body", nsmgr);
或者使用 local-name()
函数完全忽略命名空间:
XmlNode myNode = xml.SelectSingleNode(
"/*[local-name()='wordDocument']/*[local-name()='body']", nsmgr);
关于c# - 在 C# 中查找具有命名空间的 xml 文档中的特定节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29506836/