- 简短的答案:使用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 documentdocument 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 = "<urn:ResponseStatus version="1.0" xmlns:urn="urn:camera-org">rn" + // "rn" + // "<urn:requestURL>/CAMERA/Streaming/status</urn:requestURL>rn" + // "<urn:statusCode>4</urn:statusCode>rn" + // "<urn:statusString>Invalid Operation</urn:statusString>rn" + // "<urn:id>0</urn:id>rn" + // "rn" + // "</urn:ResponseStatus>";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() + ")");}


