1
我試圖解析配置文件,但是當我在節點上調用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
其他一切工作正常。