Android中的XPath没有产生java结果
我试图使用下面的代码获得XPATH的结果。不管我使用的实际XPATH表达式是什么,我总是得不到任何结果
factory.setNamespaceAware(true);
DocumentBuilder builder = null;
builder = factory.newDocumentBuilder();
doc = builder.parse(getResources().openRawResource(R.raw.cdatest02));
NodeList nodes;
String exp = "//versionNumber";
XPathFactory xfactory = XPathFactory.newInstance();
XPath xpath = xfactory.newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
public String getNamespaceURI(String s) {
if (s.equals(XMLConstants.DEFAULT_NS_PREFIX))
return doc.lookupNamespaceURI(null);
else
return doc.lookupNamespaceURI(s);
}
public String getPrefix(String s) {
return doc.lookupPrefix(s);
}
public Iterator getPrefixes(String s) {
return null;
}
});
nodes = (NodeList) xpath.evaluate(exp, doc,XPathConstants.NODESET);
Log.i("xpath results", "nothing returned");
我怀疑这个问题与XML的名称空间有关。XML声明了一个默认名称空间
XML是这样开始的(非常截断)
<?xml version="1.0" encoding="UTF-8"?>
<ClinicalDocument xmlns="urn:hl7-org:v3" xmlns:npfitlc="NPFIT:HL7:Localisation" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" classCode="DOCCLIN" moodCode="EVN">
<typeId root="2.16.840.1.113883.1.3" extension="POCD_HD000040"/>
<npfitlc:messageType root="2.16.840.1.113883.2.1.3.2.4.18.17" extension="POCD_MT000012GB01"/>/
<id root="A709A442-3CF4-476E-8377-376500E829C9"/>
<code code="1234567" codeSystem="2.16.840.1.113883.2.1.3.2.4.15"/>
<title mediaType="text/plain" representation="TXT">Patient Health Record Summary</title>
<effectiveTime value="201305192000+01"/>
<confidentialityCode code="V" displayName="very restricted" codeSystem="2.16.840.1.113883.5.25"/>
<setId root="411910CF-1A76-4330-98FE-C345DDEE5553"/>
<versionNumber value="1"/>
.... lots more lines of XML ...,
你觉得我哪里出了问题吗
# 1 楼答案
不幸的是,XPath没有默认名称空间的概念。要搜索带名称空间的文档,必须在XPath语法中使用名称空间前缀,并将前缀绑定到适当的名称空间名称。如果源文档使用了默认名称空间,那么您可能无法从上下文中获取该绑定,因此必须按语法提供它