setNamespaceContext用于默认名称空间 [英] setNamespaceContext for default namespace
问题描述
我有如下的xml.
addnumber,firstnumber,secondnumber
XML:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<addnumber xmlns="http://september.examples.com/">
<firstnumber>10</firstnumber>
<secondnumber>22</secondnumber>
</addnumber>
</soapenv:Body>
</soapenv:Envelope>
当我尝试使用以下代码从Xpath获取价值
When I try to get value from Xpath using the following code
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xml)));
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
xpath.setNamespaceContext(createContext(xml));
String value = xpath.compile("/soapenv:Envelope[1]/soapenv:Body[1]/addnumber[1]/firstnumber[1]").evaluate(document).toString();
我得到的是空值.由于我在此处给出的Xpath是addnumber [1]/firstnumber [1]的空名称空间,我该如何赋予默认名称空间的xpath?
I'm geting empty value. Since the Xpath I have given here is empty namespace of addnumber[1]/firstnumber[1] How can I give xpath of default namespace?
注意:createContext()将创建一个包含前缀URI的地图
Note:createContext() will crate a map which would contain prefix, URI
推荐答案
您可以使用任何前缀来表示默认名称空间,只要它指向相同的uri.只需在其中添加指向默认名称空间uri( http://september.examples.com/)的前缀即可.函数createContext()
,并在XPath表达式中使用它.
You can use any prefix to represent default namespace, as long as it points to the same uri. Simply add another prefix pointing to default namespace uri (http://september.examples.com/) in the function createContext()
, and use it in XPath expression.
相关问题: https://stackoverflow.com/a/6392700/2998271
这篇关于setNamespaceContext用于默认名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!