org.w3c.dom.Node上的getChildNodes()返回仅为空的节点列表
问题描述:
我试图解析配置文件,但是当我在节点上调用getChildNodes()时排除,返回的节点列表包含7个空值没有别的。org.w3c.dom.Node上的getChildNodes()返回仅为空的节点列表
我的代码:
public class MinNull {
private static final List<String> excludes = new ArrayList<>();
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
File cfgFile = new File("ver.cfg");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(cfgFile);
Element rootElement = doc.getDocumentElement();
NodeList cfg = rootElement.getChildNodes();
parseConfig(cfg);
}
private static void parseConfig(NodeList cfg) {
for (int i = 0; i < cfg.getLength(); i++) {
Node node = cfg.item(i);
String name = node.getNodeName();
switch (name) {
case "excludes":
NodeList exc = node.getChildNodes();
for(int j = 0; j < exc.getLength();j++){
Node ex = exc.item(i);
System.out.println(ex);
if(ex != null && ex.getNodeName().equals("file")){
excludes.add(ex.getTextContent());
}
}
break;
}
}
}
}
我XML文件(ver.cfg命名):
<?xml version="1.0" encoding="UTF-8"?>
<root>
<server>localhost</server>
<port>6645</port>
<project>MyApp</project>
<mainfile>MyApp.jar</mainfile>
<version>v1</version>
<excludes>
<file>Launcher.jar</file>
<file>Launch.bat</file>
<file>ver.cfg</file>
</excludes>
</root>
输出:
null
null
null
null
null
null
null
其他一切工作正常。
答
您使用了错误的指标变量
Node ex = exc.item(i);
,你应该在这里使用j
。
在这一点i = 5
,并且子节点5不存在,所以你得到的null
表明该节点不存在。