Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract value of attribute node via XPath

Tags:

xml

xpath

How can I extract the value of an attribute node via XPath?

A sample XML file is:

<parents name='Parents'>   <Parent id='1' name='Parent_1'>     <Children name='Children'>       <child name='Child_2' id='2'>child2_Parent_1</child>       <child name='Child_4' id='4'>child4_Parent_1</child>       <child name='Child_1' id='3'>child1_Parent_1</child>       <child name='Child_3' id='1'>child3_Parent_1</child>     </Children>   </Parent>   <Parent id='2' name='Parent_2'>     <Children name='Children'>       <child name='Child_1' id='8'>child1_parent2</child>       <child name='Child_2' id='7'>child2_parent2</child>       <child name='Child_4' id='6'>child4_parent2</child>       <child name='Child_3' id='5'>child3_parent2</child>     </Children>   </Parent> </parents> 

So far I have this XPath string:

//Parent[@id='1']/Children/child[@name]   

It returns only child elements, but I would like to have the value of the name attribute.

For my sample XML file, here's what I'd like the output to be:

Child_2 Child_4 Child_1 Child_3 
like image 945
Rehman Avatar asked Jan 29 '11 08:01

Rehman


People also ask

What is XPath by attribute?

Definition of XPath attribute. For finding an XPath node in an XML document, use the XPath Attribute expression location path. We can use XPath to generate attribute expressions to locate nodes in an XML document.

How do I navigate to parent node in XPath?

A Parent of a context node is selected Flat element. A string of elements is normally separated by a slash in an XPath statement. You can pick the parent element by inserting two periods “..” where an element would typically be. The parent of the element to the left of the double period will be selected.


2 Answers

//Parent[@id='1']/Children/child/@name  

Your original child[@name] means an element child which has an attribute name. You want child/@name.

like image 144
lweller Avatar answered Sep 22 '22 03:09

lweller


To get just the value (without attribute names), use string():

string(//Parent[@id='1']/Children/child/@name)

The fn:string() fucntion will return the value of its argument as xs:string. In case its argument is an attribute, it will therefore return the attribute's value as xs:string.

like image 45
acdcjunior Avatar answered Sep 22 '22 03:09

acdcjunior