Kan Li
Kan Li

Reputation: 8797

XPath function that returns whole subtree under a node

Suppose part of my document is

<div>
  <b>Hello,</b> world!
</div>
<div>
  <span>
    <b>This</b> is a <b>wonderful</b> day!
  </span>
</div>

I want to select the first div, i.e. a div whose children equals <b>Hello,</b> world!, how do I write the expression. Also How about the second one?

Of course I can have a complicated expression like //div[text()[1] = ' world' and child::b[position()=1 and text='Hello,']], but the complexity grows very fast if subtree becomes a little more complicated.

Ideally if would be good to have a function subtree and equals which returns the subtree and compares two trees, respectively, so I can simply write equals(subtree(), '<span><b>This</b> is a <b>wonderful</b> day!</span>').

Any thoughts? Is there any function that fits my need? Thanks.

Upvotes: 1

Views: 312

Answers (1)

Mike Sokolov
Mike Sokolov

Reputation: 7054

If you want to find the first div in your document, use /descendant::div[1] -- or -- (//div)[1] -- note the parens, they're required to get the right behavior here.

Comparing two elements is a more complicated question. There isn't anything built into XPath 1 for that. Some environments will support XPath 2, which defines deep-equal() -- see http://www.w3.org/TR/2005/CR-xpath-functions-20051103/#func-deep-equal.

Upvotes: 0

Related Questions