简体   繁体   中英

using xpath filter to get the entire xml document structure with filtered node

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>
/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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM