Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using xpath to locate an element

Status
Not open for further replies.

lonchi

Programmer
Jan 30, 2002
12
MX
Using xpath to locate an element

Hi
I’m having a problem changing the text value of an element in an xml file using xpath.
My file structure looks like this:
<?xml version="1.0" encoding="UTF-8"?>

<application xmlns=" name="ProjectName">
<description></description>
<contact></contact>
<NVPairs name="Global Variables">
<NameValuePair>
<name>DirLedger</name>
<value>.</value>
</NameValuePair>
<NameValuePair>
<name>DirTrace</name>
<value>.</value>
</NameValuePair>
<NameValuePair>
<name>HawkEnabled</name>
<value>false</value>
</NameValuePair>
</NVPairs>
</application>

I want to be able to find “DirLedger”

I tried these Xpath’s:
/application/NVPairs/NameValuePair [./name = 'DirLedger'] (won’t work)


//*[local-name()=”application”]/NVPairs/NameValuePair [./name = 'DirLedger'] (should work)

I remove the string “xmlns=" name="ProjectName"” it works fine.

Can any one help me with this?

Thank you
 
You were on the way to solving this for yourself!

XPath expressions do not apply the default namespace. Therefore your XPath expression does not match because the element names in the XPath expression are not modified by any namespace, whereas all of the XML documents elements at and subordinate to the application element are modified by the default namespace.

You could do something like
Code:
 /*[local-name() = 'application']/*[local-name() = 'NVPairs']/*[local-name() = 'NameValuePair']/*[local-name() = 'name' and text() = 'DirLedger']/parent::*
which might usefully be abbreviated, depending on you needs, to
Code:
//*[local-name() = 'name' and text() = 'DirLedger']/..

There are other ways to do this in XSLT, but that does not appear to be your situation.

Tom Morrison
 
Thank you Tom

You sure gave me some guidance.
My next question will be how to access the text between the value nodes.
I my case, for the node with name =’DirLedger’ the value or text is “.” (dot).
I need to the dot specifically

Once again thank you.

Lonchi
 
Lonchi,

The XPath expressions I presented in my previous post get you to the NameValuePair element for which the name element's text node has the value 'DirLedger'. So, all you would need to do would be to append
Code:
/*[local-name() = 'value']/text()
to the XPath expression.

Tom Morrison
 
Tom

Your solution worked fine, thank you.

Lonchi
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top