1

Source XML document:

<library>
  <shelf>
    <list>
      <book>
        <author>
          <name>Name_001</name>
          <number>Auth_001</number>
        </author>
        <title>Title_001</title>
        <isbn>Isbn_001</isbn>
      </book>
      <book>
        <author>
          <name>Name_002</name>
          <number>Auth_002</number>
        </author>
        <title>Title_002</title>
        <isbn>Isbn_003</isbn>
      </book>
      <book>
        <author>
          <name>Name_003</name>
          <number>Auth_003</number>
        </author>
        <title>Title_003</title>
        <isbn>Isbn_003</isbn>
      </book>
    </list>
  </shelf>
</library>

Xpath in Java to get the below output (example filter by author number) filter expression something similar "/library/shelf/list/book/author[number='Auth_002']"?

Output:
<library>
  <shelf>
    <list>
      <book>
      <author>
          <name>Name_002</name>
          <number>Auth_002</number>
        </author>
        <title>Title_002</title>
        <isbn>Isbn_003</isbn>
      </book>
    </list>
  </shelf>
</library>
Emel
  • 11
  • 2

2 Answers2

0
/library/shelf/list/book/author[number='Auth_002']/ancestor-or-self::* | /library/shelf/list/book/author[number='Auth_002']/preceding-sibling::* | /library/shelf/list/book/author[number='Auth_002']/ancestor::*[1]/following-sibling::*

The "OR's" denoted by "|" are added to ensure some nodes like <name> or <title> are also included.

PS - I have worked around the Xpath provided by you, you can try optimizing it according to your requirements.

Hopefully this answers your query.

  • This selects a set of nodes with overlapping subtrees; I find it hard to imagine how such a result could be useful. However, it's a legitimate way to respond to a rather confusing requirements statement. I've tried a different way. – Michael Kay Jul 13 '21 at 22:48
0

An XPath expression can only select nodes that are actually present in the source document - it can't perform transformations on them. So you could select the desired book element using //book[author/name="Name_002"]; but the library, shelf, and list elements in your result are not present in the source and therefore cannot be selected. (Your result includes a list element with a single child, and there is no list element with a single child in the source document.)

Note that this expression will select a single book element. There are two popular ways of displaying the node selected by an XPath expression:

(a) by showing its content (descendants):

  <book>
    <author>
      <name>Name_002</name>
      <number>Auth_002</number>
    </author>
    <title>Title_002</title>
    <isbn>Isbn_003</isbn>
  </book>

(b) by showing its path (ancestors)

/library[1]/shelf[1]/list[1]/book[2]

But these are simply different ways of presenting the result. The actual result is a single node named book.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164