tags:

views:

32

answers:

2

Hi I'm trying to get a variable value (ref within contractRef) in the xml below, but when I use what I assume to be the xpath:

/discovery/contractRef[@xmlns='http://schemas.xmlsoap.org/disco/scl/']/@ref

it returns nothing. How can I get this variable, what am I missing? Thanks

<?xml version="1.0" encoding="utf-8"?>
<discovery xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/disco/"&gt;
  <contractRef ref="http://127.0.0.1/Services/Core/Calendar/LBCalendar.svc?wsdl" docRef="http://127.0.0.1/Services/Core/Calendar/LBCalendar.svc" xmlns="http://schemas.xmlsoap.org/disco/scl/" />
</discovery>
A: 

I actually uploaded your xml to http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm and it I think your xpath is working.

Mike Cheel
It's not working, that is why I posted a question. Thanks for checking though.
Martin
+4  A: 

This is a FAQ. The element <discovery> is in the namespace http://schemas.xmlsoap.org/disco/ and the child element <contractRef> is in the namespace http://schemas.xmlsoap.org/disco/scl/ You need to register these namespaces with some prefix and then use those prefixes in your XPath expression. How "registering" is done, depends on the language/environment where the XPath expression is used. If the XPath is used inside an XML document, then prefixes are "registered" just by declaring a prefixed namespace, for example xmlns:scl="http://schemas.xmlsoap.org/disco/scl/"

Let's assume that http://schemas.xmlsoap.org/disco/ is registered to prefix d and http://schemas.xmlsoap.org/disco/scl/ is registered to prefix scl then a correct XPath expression would be

/d:discovery/scl:contractRef/@ref

Namespaces are a fundamental feature in XML and XPath. Please take time to learn them. A hack to avoid using namespace prefixes in XPath expressions is to use local-name() function

/*[local-name() = 'discovery*]/*[local-name() = 'contractRef']/@ref

Note that the attribute name doesn't need a namespace prefix since it belongs to no-namespace.

jasso
Thank you for your informative answer
Martin
@jasso: +1 Good answer. A minor: from question it looks like @Martin is trying to test for an `xmlns` attribute. It must point out that namespace declaration are not attributes, acording to XDM and XML Infoset, in scope namespaces are accessed by a different accessor.
Alejandro