下面是代码的简单部分:
String test = "<?xml version="1.0" encoding="UTF-8"?><TT_NET_Result><GUID>9145b1d3-4aa3-4797-b65f-9f5e00be1a30</GUID></TT_NET_Result>"
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(test)));
NodeList nl = doc.getDocumentElement().getElementsByTagName("TT_NET_Result");问题是我没有得到任何结果-- nodelist变量"nl“是空的。会出什么问题呢?
发布于 2011-09-14 17:37:02
请求的是document元素下的元素,但TT_NET_Result是document元素。如果你只是打电话给
NodeList nl = doc.getElementsByTagName("TT_NET_Result");那么我怀疑你会得到你想要的结果。
发布于 2017-11-03 22:49:59
这是对这个老问题的另一个回答。我今天在我的代码中遇到了类似的问题,实际上我一直在读/写XML。由于某种原因,我忽略了一个主要事实。如果您想要使用
NodeList elements = doc.getElementsByTagNameNS(namespace,elementName);您需要使用支持名称空间的工厂来解析您的文档。
private static DocumentBuilderFactory getFactory() {
if (factory == null){
factory = DocumentBuilderFactory
.newInstance();
factory.setNamespaceAware(true);
}
return factory;
}https://stackoverflow.com/questions/7414184
复制相似问题