tags:

views:

107

answers:

4

Example of what I'm looking for. Here is the input:

<AAA>
  <BBB id='1'>
    <CCC  id='1'>
       <DDD  id='1'/>
       <DDD  id='2'/> 
    </CCC>
    <CCC id='2'>
       <DDD  id='3'/>
       <DDD  id='4'/> 
    </CCC>
  </BBB>
  <BBB id='2'>
    <CCC  id='3'>
       <DDD  id='5'/>
       <DDD  id='6'/> 
    </CCC>
    <CCC id='4'>
       <DDD  id='7'/>
       <DDD  id='8'/> 
    </CCC>
  </BBB>
</AAA>

Here is the node set I want to select (DDD with id 1, it's parent and grandparent):

  <BBB id='1'>
    <CCC  id='1'>
       <DDD  id='1'/>
    </CCC>
  </BBB>

In other words, the direct line from self to grandparent, and only those nodes.

A: 
AAA\BBB[CCC\DDD\@id = '1']
aJ
That returns siblings and uncles of DDD with id=1. I don't want siblings or uncles.Thanks, though.
John Q.
A: 

Assuming the starting point is the DDD with @id = 1:

. | parent::CCC | ancestor::BBB

Returns a node set containing DDD, its parent and its grandparent.

Welbog
+1  A: 

The result of any XPath expression will be either a single node or a list of nodes; you will not be able to get a tree structure using XPath alone.

However, you can select the nodes you requested: you'll just get a list of them instead of a hierarchy.

Here is a simple XPath that will accomplish this:

//DDD[@id = '1'] | //DDD[@id = '1']/.. | //DDD[@id = '1']/../..

Note that using the // path can have performance implications. You may wish to expand the // to /AAA/BBB/CCC/

If you want to play around with this, you can run XPath expressions on arbitrary XML using my online tool, here.

Good luck!

Chris Nielsen
A: 

I now think that my question does not make sense. In reality, I'm trying to solve a document building problem with a just an XPath - XPath is not enough. Thanks to all who responded.

John Q.