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.2k views
in Technique[技术] by (71.8m points)

xml - Select first instance only with XPath?

I am parsing some XML something like this:

<root>
    <some_gunk/>
    <dupe_node>
        ...
        stuff I want
        ...
    </dupe_node>
    <bits_and_pieces/>
    <other_gunk/>
    <dupe_node>
        ...
        stuff I don't want
        ...
    </dupe_node>
    <more_gunk/>
</root>

An XPath of '//dupe_node' will give me two instances of dupe_node to play with. I only want to traverse the first. Can I do this with XPath?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
/descendant::dupe_node[1]

//dupe_node[1] is generally wrong, although it produces an identical result in this particular case. See docs:

The location path //para[1] does not mean the same as the location path /descendant::para[1]. The latter selects the first descendant para element; the former selects all descendant para elements that are the first para children of their parents.

Given the following XML:

<foo>
    <bar/>
    <foo>
        <bar/>
    </foo>
</foo>

//bar[1] will produce two nodes, because both bars are first children of their respective parents.

/descendant::bar[1] will give only one node, which is the first of all the bars in the document.


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

...