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 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<ns1:schema xmlns:ns1='http://example.com'>"
+ "<ns1:tag1>"
+ "<ns1:tag2>value</ns1:tag2>"
+ "</ns1:tag1>"
+ "</ns1:schema>";
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 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<ns1:schema xmlns:ns1='http://example.com'>"
+ "<ns1:tag1>"
+ "<ns1:tag2>value</ns1:tag2>"
+ "</ns1:tag1>"
+ "</ns1:schema>";
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