我得到了需要解析的HTML,并且使用C#和HTML敏捷包库来选择节点。我的html看起来像:

<input data-translate-atrr-placeholder="FORGOT_PASSWORD.FORM.EMAIL">

或:
<h1 data-translate="FORGOT_PASSWORD.FORM.EMAIL"></h1>

其中data-translate-attr-****是我需要找到的新属性模式
我可以用这样的东西:
//[contains(@??,'data-translate-attr')]

但不幸的是,这只会搜索属性中的值。如何使用通配符查找属性本身?
更新:@Mathias Muller
HtmlAgilityPack.HtmlDocument htmlDoc
// this is the old code (returns nodes)
var nodes = htmlDoc.DocumentNode.SelectNodes("//@data-translate");
// these suggestions return no nodes using the same data
var nodes = htmlDoc.DocumentNode.SelectNodes("//@*[contains(name(),'data-translate')]");
var nodes = htmlDoc.DocumentNode.SelectNodes("//@*[starts-with(name(),'data-translate')]");

更新2
这似乎是一个Html敏捷包问题,而不是XPath问题,我使用chrome测试我的XPath表达式,以下所有内容都在chrome中工作,但不是在Html敏捷包中:
//@*[contains(local-name(),'data-translate')]
//@*[starts-with(name(),'data-translate')]
//attribute::*[starts-with(local-name(.),'data-translate')]

我的解决方案
我最后只是用传统的方式做事。。。
var nodes = htmlDoc.DocumentNode.SelectNodes("//@*");

if (nodes != null) {
    foreach (HtmlNode node in nodes) {
        if (node.HasAttributes) {
            foreach (HtmlAttribute attr in node.Attributes) {
                if (attr.Name.StartsWith("data-translate")) {
                    // code in here to handle translation node
                }
            }
        }
    }
}

最佳答案

使用XPath函数contains()starts-with()。您需要一个XPath表达式,如

//@*[contains(name(),'data-translate')]

或者也许
//@*[starts-with(name(),'data-translate')]

它实际上检索属性节点。上面的@*是您要查找的属性通配符。

关于c# - 使用XPath选择带通配符的属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29802310/

10-12 17:11
查看更多