Jan
Jan

Reputation: 343

XPath: Select root, filter child elements

Consider the following XML-document:

<inst>
  <ins>
    <id>id_01</id>
    <pos>1</pos>
  </ins>
  <ins>
    <id>id_02</id>
    <pos>1</pos>
  </ins>
</inst>

I try to get the following output:

<inst>
  <ins>
    <id>id_01</id>
    <pos>1</pos>
  </ins>
</inst>

I wrote the following XQuery/XPath-Expression:

doc('database/data.xml')/inst[ins/id='id_01']

This does not give the wanted result but the whole document, just as if no filtering condition would be there.. But if i put in id's that are not present in the XML-Document, the result is empty.

I just don't know what is wrong with this statement.

Upvotes: 3

Views: 2301

Answers (2)

bosari
bosari

Reputation: 2000

You can write something like-

<inst>{doc('database/data.xml')/inst/ins[id eq "id_01"]}</inst>
The "value comparison" operators (eq, lt, etc.) are designed for comparing single values, so better to use 'eq'

Upvotes: -2

kjhughes
kjhughes

Reputation: 111601

The XPath you wrote,

/inst[ins/id='id_01']

says to select the inst root element that contain a ins child element with a child element whose string value is "id_01". Since the root of your XML does indeed meet this criteria, it is selected:

<inst>
  <ins>
    <id>id_01</id>
    <pos>1</pos>
  </ins>
  <ins>
    <id>id_02</id>
    <pos>1</pos>
  </ins>
</inst>

You could instead use this XPath,

/inst/ins[id='id_01']

to select just this XML,

<ins>
  <id>id_01</id>
  <pos>1</pos>
</ins>

however, there is no XPath that will select the root element without the second ins element as you seem to be trying to do. The reason is that XPath is for selection, not transformation of XML. There is no inst element in your XML that can be selected that lacks the second (id_02) ins element. If you want to transform XML, use XSLT instead.

Upvotes: 3

Related Questions