【问题标题】:SelectNodes returning 0 elementsSelectNodes 返回 0 个元素
【发布时间】:2021-12-10 01:09:51
【问题描述】:

我对命名空间失去了理智。在关注了大多数关于如何使用的帖子之后,我终生无法弄清楚如何使用 SelectNodes。

我的 xml:

<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <Fragment>
    <ComponentGroup Id="ProgramFiles">
      <Component ..../>
      <Component ..../>
      <Component ..../>

我尝试过的:

 xnManager = new XmlNamespaceManager(doc.NameTable);
 xnManager.AddNamespace("wx", "http://schemas.microsoft.com/wix/2006/wi");

 //XmlNodeList aNodes = doc.SelectNodes("//wx:Wix/wx:Fragment/wx:ComponentGroup/Component", xnManager);

 //var aNodes = doc.GetElementsByTagName("wx:Wix/Fragment/ComponentGroup/Component");

 //System.Xml.XmlNodeList aNodes = doc.SelectNodes("//*[local-name()=\"Component\"]");

我错过了什么?所有结果返回 0 个元素。文档有效并加载到文档中。

【问题讨论】:

  • 请提供一个可重现的最小示例。

标签: xml namespaces xmldocument xmlnode selectnodes


【解决方案1】:

请尝试以下概念示例。

它正在使用 LINQ to XML API。

c#

void Main()
{
    XDocument xdoc = XDocument.Parse(@"<Wix xmlns='http://schemas.microsoft.com/wix/2006/wi'>
        <Fragment>
            <ComponentGroup Id='ProgramFiles'>
                <Component>One</Component>
                <Component>Two</Component>
                <Component>Three</Component>
            </ComponentGroup>
        </Fragment>
    </Wix>");

    XNamespace ns = xdoc.Root.GetDefaultNamespace();
    foreach (XElement xelem in xdoc.Descendants(ns + "Component"))
    {
        Console.WriteLine(xelem.Value);
    }
}

输出

One
Two
Three

【讨论】:

  • 漂亮、简洁的代码(+1)。可能想补充一下为什么 OP 的 XPath 尝试失败了:前两个忽略了默认命名空间中的 all 后代元素;第三个 XPath 看起来不错——问题可能出在支持代码或其他地方。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-19
相关资源
最近更新 更多