在 C# 中使用命名空间在 xml 文档中查找特定节点

Finding specific node in xml document with namespace in C#

我在 Whosebug for solving my problem like this one 中尝试了很多答案。但是 none 似乎适用于我的 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总是returnsnull

谁能告诉我我做错了什么?

您的代码有问题:

  • 要获取用于给定前缀的命名空间(在本例中为 w),您应该检查正确的 xmlns:w 属性(不是默认的 xmlns,也不是随机的 xmlns:alm) 或者在大多数情况下简单地明确指定 - 因为它永远不会在有效的 WordML 文档的情况下改变。
  • 到从根开始的 select 元素,您需要使用从根开始的 XPath 搜索 (/w:....) 或在以根元素作为子元素的节点上执行 select(文档本身)。

工作代码的可能变体:

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