tags:

views:

71

answers:

3

Hi,
i will give an example of the problem i have. My XML is like this

<root>
  <child Name = "child1">
  <node>
  <element1>Value1</element1>
  <element2>Value2</element2>
  </node>
  </child>
  <child Name = "child2">
  <element1>Value1</element1>
  <element2>Value2</element2>
  <element3>Value3</element3>
  </child>
</root>

I have xpath expression that returns all "element2" nodes. Then i want to for every node of type "element2" to find the node of type "child" that contains it. The problem is that between these two nodes there can be from 1 to n different nodes so i can't just use "..". Is there something like "//" that will look up instead of down

I have some basic knowledge of xpath and according http://www.w3schools.com/xpath/xpath_syntax.asp "..' returns current node parent the problem is that the current node is "element2" and the problem is that the xml is dynamic comes from third party library so i can have xml like this

<child Name = "child1">
  <node>
  <element1>Value1</element1>
  </node>
</child>

or like this

<child Name = "child1">
  <node1>
   <node2>
    <node3>
     <element1>Value1</element1>
     <element2>Value2</element2>
    </node3>
   </node2>
  </node1>
</child>

There can be more then 3 nodes between "element" and child an the number of nodes vary form 1 to 20. Please give me an example of just one xpath query to get the "child" node in both cases using just ".."

Best Regards,
Iordan

+3  A: 

The ancestor xpath axis is what you are looking for:

element2/ancestor::child

The ancestor axis returns all the elements that contain the context element, going upward.

James Sulak
+3  A: 

So your current context is the element2 element? Use the parent axis:

parent::child/@Name

That will get the parent of the current element, named child, and get its attribute Name.

If you're not in the context of element2 and you want to find all child elements with element2 children, you need this one instead:

child[element2]
Welbog
@IordanTanev: BTW, the shortcut for `parent::*` is `..`, so `../@Name` would work perfectly as well.
Tomalak
+3  A: 

Use the .. operator.

AndyC