XPath - 选择所选子节点的文本

html-agility-pack xpath

鉴于我有一个以下的xml:

<div id="Main">
    <div class="quote">
        This is a quote and I don't want this text
    </div> 
    <p>
        This is content.
    </p>
    <p>  
        This is also content and I want both of them
    </p>
</div>

是否有“XPath”来帮助我选择div#Main的内部文本作为单个节点 ,但必须排除任何div.quote的文本。

我只想要文字: “这是内容。这也是内容,我想要他们两个”

提前致谢

这是测试XPath的代码,我使用.NET和HtmlAgilityPack,但我相信xPath应该适用于任何语言

[Test]
public void TestSelectNode()
{
    // Arrange 
    var html = "<div id=\"Main\"><div class=\"quote\">This is a quote and I don't want this text</div><p>This is content.</p><p>This is also content and I want both of them</p></div>";
    var xPath = "//div/*[not(self::div and @class=\"quote\")]/text()";

    var doc = new HtmlDocument();
    doc.LoadHtml(html);

    // Action
    var node = doc.DocumentNode.SelectSingleNode(xPath);

    // Assert
    Assert.AreEqual("This is content.This is also content and I want both of them", node.InnerText);
}

测试失败显然是因为xPath仍然不正确。

Test 'XPathExperiments/TestSelectNode' failed:
    Expected values to be equal.

    Expected Value : "This is content.This is also content and I want both of them"
    Actual Value   : "This is content."

一般承认的答案

我不认为有一个XPath会将此作为单个节点,因为您尝试获取的值不是单个节点。有没有理由你不能这样做?

StringBuilder sb = new StringBuilder();
// Action
var nodes = doc.DocumentNode.SelectNodes(xPath);
foreach(var node in nodes)
{
   sb.Append(node.InnerText);
}

// Assert
Assert.AreEqual("This is content.This is also content and I want both of them", 
                sb.ToString());

热门答案

你想要div的任何孩子的文本不是div与类引用:

div/*[not(self::div and @class="quote")]/text()


许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因
许可下: CC-BY-SA with attribution
不隶属于 Stack Overflow
这个KB合法吗? 是的,了解原因