XPath for hierarchical column / name-value properties?
I am trying to find the XPath of the below XML. Its consists of properties array list. I need to fetch the value for ‘COMPUTER’.
<output xmlns:tns="http://www.ariuy.org/" custname="marcus" > <tns:column name="customer_english_name">marcus ag</tns:column> <tns:column name="customer_primary_name">marcus ag</tns:column> <tns:reqline> <tns:orderline user_item_description="xyz"> <tns:column name="properties"> <tns:column name="name">COMPUTER</tns:column> <tns:column name="value">HCL </tns:column> </tns:column> <tns:column name="properties"> <tns:column name="name">LAPTOP</tns:column> <tns:column name="value">HP</tns:column> </tns:column> <tns:column name="properties"> <tns:column name="name">PHONE</tns:column> <tns:column name="value">MI</tns:column> </tns:column> <tns:column name="properties"> <tns:column name="name">JOB</tns:column> <tns:column name="value">Developer</tns:column> </tns:column> ...... </tns:orderline> </tns:reqline> </output>
I have tried
/tns:output/tns:reqline/tns:OrderLine/tns:properties[@name='COMPUTER']/@value
but it is not working.
To fecth HCL
(value under COMPUTER
), you can go with :
(//*[name()="tns:column"][@name="properties"])[1]/*[2]/text()
Look for the first column element with a specific attribute of the page. Then select its second child.
Or more secure option :
//*[name()="tns:column"][preceding-sibling::*[name()="tns:column"][.="COMPUTER"]]/text()
Look anywhere for a column element where its preceding-sibling contains the value "COMPUTER".
Assuming that you have the namespace prefix tns
properly declared to abbreviate the http://www.ariuy.org/
namespace value…
This XPath,
/output/tns:reqline/tns:orderline /tns:column[@name='properties'][tns:column[@name='name']='COMPUTER'] /tns:column[@name='value']
will select
<tns:column name="value">HCL </tns:column>
as requested.
You say:
/tns:output/tns:reqline/tns:OrderLine/tns:properties[@name=’COMPUTER’]/@value
Well
(a) the output
element is not in the tns namespace
(b) the orderline
element starts with o
not O
(c) you don’t have an element called tns:properties
(d) there’s no @name
attribute whose value is "COMPUTER"
(e) there’s no @value
attribute anywhere.
That’s a lot of errors for one line of code.
Others have given you working solutions, but I think it’s important you understand why your attempt is wrong.