开发者

Is this simple XPath query correct?

I have a document that has the following format:

<Root>
    <A />
    <C />
    <B />
    <A>
        <B>
            <A />
            <C /> 
        </B>
    </A>
</Root>

I want to "catch" 开发者_Python百科all the elements A and B and list them in a new doc:

<A /> <B /> <A /> <B /> ...

With XPath, would the query be (with Root as the context node):

.//*[A | B]


Use:

//*[self::A or self::B]

This selects all elements in the document that are either A or B.

Traverses the document only once :)


Based on Welbog's answer, I came up with this one:

.//*[name()="A" or name()="B"]

It does what is supposed.


You could simply write //A|//B (The previous one didn't seem to work except in one online xpath tester, that'll teach me to trust them). Although this would traverse the tree twice.

Your original expression said: give me all the elements (//*) that have a child called A or B ([A|B]), because when the predicate part (the [] bit) is evaluated, the context node is alraedy the node you're examining, so anything within the predicate is relative to that context.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜