Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

getting first node in xpath result set

I am trying to select the first element in a set of resulting nodes after executing an xpath query.

When I do this:

//dl

I get the following result set:

[<dl>?…?</dl>?, <dl>?…?</dl>?]

How can I get the first one? Neither of these work:

//dl[1]
//dl[position()=1]

I am executing this in Chrome's Web Inspector.

question from:https://stackoverflow.com/questions/9199415/getting-first-node-in-xpath-result-set

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the following:

(//dl)[1]

The parentheses are significant. You want the first node that results from //dl (not the set of dl elements that are the first child of their parent (which is what //dl[1] (no parens) returns)).

This is easier to see when one realizes that // is shorthand for (i.e. expands fully to) /descendant-or-self::node()/ so that //dl[1] is equivalent to:

/descendant-or-self::node()/dl[1]

...which is more obviously not what you want. Instead, you're looking for:

(/descendant-or-self::node()/dl)[1]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...