java名称空间_Java中具有名称空间的XPath

小编典典

简短的答案:使用XPath local-name()。这样:xPathFactory.newXPath().compile("//*[local-name()='requestURL']/text()");将返回/CAMERA/Streaming/status

或者,您可以实现一个NamespaceContext映射名称空间名称和URI的,并在查询之前在XPath对象上对其进行设置。

看一下这篇博客文章, 更新: 该文章已结束,您可以在webarchive上看到它

解决方案1样本:

XPath xpath = XPathFactory.newInstance().newXPath();

String responseStatus = xpath.evaluate("//*[local-name()='ResponseStatus']/text()", document);

System.out.println("-> " + responseStatus);

解决方案2样本:

// load the Document

Document document = ...;

NamespaceContext ctx = new NamespaceContext() {

public String getNamespaceURI(String prefix) {

return prefix.equals("urn") ? "urn:camera-org" : null;

}

public Iterator getPrefixes(String val) {

return null;

}

public String getPrefix(String uri) {

return null;

}

};

XPath xpath = XPathFactory.newInstance().newXPath();

xpath.setNamespaceContext(ctx);

String responseStatus = xpath.evaluate("//urn:ResponseStatus/text()", document);

System.out.println("-> " + responseStatus);

编辑

这是一个完整的示例,它可以正确检索元素:

String xml = "\r\n" + //

"\r\n" + //

"/CAMERA/Streaming/status\r\n" + //

"4\r\n" + //

"Invalid Operation\r\n" + //

"0\r\n" + //

"\r\n" + //

"";

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

factory.setNamespaceAware(true);

DocumentBuilder builder = factory.newDocumentBuilder();

Document doc = builder.parse(new java.io.ByteArrayInputStream(xml.getBytes()));

XPath xpath = XPathFactory.newInstance().newXPath();

xpath.setNamespaceContext(new NamespaceContext() {

public String getNamespaceURI(String prefix) {

return prefix.equals("urn") ? "urn:camera-org" : null;

}

public Iterator> getPrefixes(String val) {

return null;

}

public String getPrefix(String uri) {

return null;

}

});

XPathExpression expr = xpath.compile("//urn:ResponseStatus");

Object result = expr.evaluate(doc, XPathConstants.NODESET);

NodeList nodes = (NodeList) result;

for (int i = 0; i < nodes.getLength(); i++) {

Node currentItem = nodes.item(i);

System.out.println("found node -> " + currentItem.getLocalName() + " (namespace: " + currentItem.getNamespaceURI() + ")");

}

2020-09-08

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值