【问题标题】:C# XPath not selects some child nodesC# XPath 不选择某些子节点
【发布时间】:2016-07-29 13:18:34
【问题描述】:

我正在尝试使用 XPath 表达式:.//*[@class='newsContent newsClosed']/b,但它不起作用,总是返回 0 个元素。

然后我尝试更改.//*[@class='newsContent newsClosed'] 上的表达式,并且成功了。

为什么第一个表达式不起作用?

我使用XmlDocument.SelectSingleNode 来检索元素。

XHTML 的一部分:

<div class="newsContent newsClosed">
    <b>some text that I need to take</b>
    <br />
    <p>
        text
    </p>
    <p>
        <b>text</b>
        <br />
        <b>text</b>
        <b>text</b>
    </p>
...

在 FirePath 中,两个表达式都可以正常工作。

【问题讨论】:

标签: c# xml xpath xmldocument


【解决方案1】:

假设这是 XHTML,那么您需要指定元素的 命名空间http://www.w3.org/1999/xhtml

var resolver = new XmlNamespaceManager(new NameTable());

resolver.AddNamespace("html", "http://www.w3.org/1999/xhtml");

var result = doc.SelectSingleNode(
    ".//*[@class='newsContent newsClosed']/html:b", resolver);

我个人的偏好是完全放弃 XPath 并使用 LINQ to XML:

XNamespace html = "http://www.w3.org/1999/xhtml";

var result = (string) doc.Descendants()
    .Where(element => (string) element.Attribute("class") == "newsContent newsClosed")
    .Elements(html + "b")
    .Single();

请参阅this fiddle 以获取演示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    相关资源
    最近更新 更多