无法使用DOM解析器读取带有名称空间前缀的xml

这是输入XML:

     A00179-02     

这是我用来读取XML的代码(变量xmlString包含上面的XML):

 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xmlString)); Document doc = db.parse(is); System.out.println("Element :" + doc.getElementsByTagName("Token").item(0)); System.out.println("Element :" + doc.getElementsByTagName("ns2:Token").item(0)); 

输出:

 Element :null Element :[ns2:Token: null] 

如果我使用“ns2:Token”作为标记名称,我能够读取元素,但我不想在我的代码中使用前缀,因为我不确定它是否相同或更改未来。 有没有办法在不对标记名称中的命名空间进行硬编码的情况下读取xml元素?

命名空间元素的W3C dom方法:

 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 

IIRC早期版本的W3C DOM对名称空间的支持很少,所以我不使用它。 但是,如果您使用上面的完整namespaceURI http://schemas.xmlsoap.org/soap/envelope/它应该工作。 前缀不重要 – 它在使用它的文档之外没有永久性。

所以尝试:

 System.out.println("Element :" + doc.getElementsByTagNameNS( "http://schemas.xmlsoap.org/soap/envelope/", "Token").item(0)); 

首先获取命名空间

 docFactory.setNamespaceAware(true); StringBuilder nameSpace = new StringBuilder( doc.getDocumentElement().getPrefix() != null ? doc.getDocumentElement().getPrefix() + ":" : ""); 

然后累积使用nameSpace变量

例如:

 Node node= doc.getElementsByTagName(nameSpace + "Node1").item(0) .getFirstChild(); 

您始终可以将命名空间分配给变量,这样可以在将来动态更改它。

尝试使用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); }