What would be the xpath for this xml
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/">
<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>
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.
I actually uploaded your xml to http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm and it I think your xpath is working.
精彩评论