Java 无法使用DOM解析器读取具有命名空间前缀的xml
这是输入XML:Java 无法使用DOM解析器读取具有命名空间前缀的xml,java,xml,dom,xml-parsing,Java,Xml,Dom,Xml Parsing,这是输入XML: <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <SOAP-ENV:Body> <ns2:SendResponse xmlns:ns2="http://mycompany.com/schema/"> <ns2:SendResult>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<ns2:SendResponse xmlns:ns2="http://mycompany.com/schema/">
<ns2:SendResult>
<ns2:Token>A00179-02</ns2:Token>
</ns2:SendResult>
</ns2:SendResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
输出:
Element :null
Element :[ns2:Token: null]
如果使用“ns2:Token”作为标记名,我可以读取元素,但我不想在代码中使用前缀,因为我不确定它将来是否相同或更改。有没有办法读取xml元素而不在标记名中硬编码名称空间?您可以始终将名称空间分配给变量,这将允许将来动态更改它。名称空间元素的方法:
getElementsByTagNameNS
NodeList getElementsByTagNameNS(String namespaceURI,
String localName)
Returns a NodeList of all the Elements with a given local name and namespace URI in document order.
Parameters:
namespaceURI - The namespace URI of the elements to match on. The special value "*" matches all namespaces.
localName - The local name of the elements to match on. The special value "*" matches all local names.
Returns:
A new NodeList object containing all the matched Elements.
Since:
DOM Level 2
W3CDOM的IIRC早期版本对名称空间的支持很差,所以我不使用它。但是,如果将上述内容与完整的namespaceURIhttp://schemas.xmlsoap.org/soap/envelope/
它应该可以工作。前缀并不重要-它在使用它的文档之外没有永久性
因此,请尝试:
System.out.println("Element :" + doc.getElementsByTagNameNS(
"http://schemas.xmlsoap.org/soap/envelope/", "Token").item(0));
尝试使用XPath表达式。请参见下面的示例代码
Document doc = dBuilder.parse(new ByteArrayInputStream(responseXML.getBytes()));
doc.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/ns6:ReadPersonReturn/ns6:object/ns3:Person/ns3:Phone/ns3:item";
NodeList nodes = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
Element secondNode = null;
if(nodes != null && nodes.getLength() > 0){
secondNode = (Element) leadCloudPingRecordNodes.item(i);
}
首先获取名称空间
docFactory.setNamespaceAware(true);
StringBuilder nameSpace = new StringBuilder(
doc.getDocumentElement().getPrefix() != null ? doc.getDocumentElement().getPrefix() + ":" : "");
然后根据需要使用名称空间变量
例如:
docFactory.setNamespaceAware(true);
StringBuilder nameSpace = new StringBuilder(
doc.getDocumentElement().getPrefix() != null ? doc.getDocumentElement().getPrefix() + ":" : "");
Node node= doc.getElementsByTagName(nameSpace + "Node1").item(0)
.getFirstChild();