XPath expression to select the complete document excluding one element

Viewed 42

I have an XML document

<root>
    <a>Foo</a>
    <b>Bar</b>
    <c>Baz</c>
</root>

and need an XPath 1.0 query to obtain the entire document excluding the <b> element, as follows:

<root>
    <a>Foo</a>
    <c>Baz</c>
</root>

I have tried *[not(self::b)] but this just gives me the original document, as does *[not(ancestor-or-self::b)].

The queries /root/*[not(self::b)] and /root/*[not(ancestor-or-self::b)] work as expected to exclude the element, but omit the parent root element, which we require.

<a>Foo</a>
<c>Baz</c>

Any suggestions on how to achieve this would be gratefully received.

1 Answers

XPath can only select nodes that are there in the input, it cannot modify the input tree in any way. Your input does not contain a root element whose only children are a and c, so you cannot select such an element.

For that you need XSLT or XQuery.

Related