为什么getElementsByTagNameNS在java中为空?

我想得到tag2的值,我得到了一个xml:

String xml = "" + "" + "" + " value" + "" + ""; 

然后将其解析为文档,并希望通过tagnameNS获取元素。 但是当我运行这个时,nodelist为空为什么?

 DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(true); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new InputSource(new StringReader(xml))); NodeList nl = doc.getElementsByTagNameNS("http://example.com", "tag2"); String a = nl.item(0).getNodeValue(); 

仍然无法使用URI。

getElementsByTagNameNS正在返回结果。 问题是您当前正在调用错误的方法来从结果元素中获取文本内容。 你需要调用getTextContext()而不是getNodeValue()

 String a = nl.item(0).getTextContent(); 

DomDemo

下面是一个完整的代码示例。

 package forum13166195; import java.io.StringReader; import javax.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.InputSource; public class DomDemo { public static void main(String[] args) throws Exception{ String xml = "" + "" + "" + "value" + "" + ""; DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(true); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new InputSource(new StringReader(xml))); NodeList nl = doc.getElementsByTagNameNS("http://example.com", "tag2"); String a = nl.item(0).getTextContent(); System.out.println(a); } } 

产量

 value 

替代方法

您还可以使用javax.xml.xpath API(包含在Java SE 5及更高版本中)来查询XML文档中的值。 这些API提供了比getElementsByTagNameNS更多的控制。

XPathDemo

 package forum13166195; import java.io.StringReader; import java.util.Iterator; import javax.xml.namespace.NamespaceContext; import javax.xml.xpath.*; import org.xml.sax.InputSource; public class XPathDemo { public static void main(String[] args) throws Exception{ String xml = "" + "" + "" + "value" + "" + ""; XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(new NamespaceContext() { public String getNamespaceURI(String arg0) { if("a".equals(arg0)) { return "http://example.com"; } return null; } public String getPrefix(String arg0) { return null; } public Iterator getPrefixes(String arg0) { return null; } }); InputSource inputSource = new InputSource(new StringReader(xml)); String result = (String) xpath.evaluate("/a:schema/a:tag1/a:tag2", inputSource, XPathConstants.STRING); System.out.println(result); } } 

产量

 value 
  Try this : DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(true); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new InputSource(new StringReader(xml))); NodeList nodeList = doc.getElementsByTagNameNS("*", "tag2"); String a = nodeList.item(0).getTextContent(); System.out.println(a); 

产量

 value 

您需要传递命名空间URL; 不是您在XML中创建的本地别名。