我正在尝试使用xml文件访问用户指定文件的位置,但是使用我创建的一个文件,我不断获得一种方法的#text文本,而另一种却给出了[Settings:null]
package tests;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import utils.Cryption;
import utils.CryptoException;
public class Test {
public static void main(String[] args) throws CryptoException, SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("D:\\Projects\\Utils\\exampleSettings.xml"));
NodeList nodes = document.getElementsByTagName("Settings");
for(int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
System.out.println(element.toString());
}
Element rootElement = document.getDocumentElement();
String hold = getSeting("debugLocation", rootElement);
System.out.println(hold);
}
private static String getSeting(String tagName, Element element) {
NodeList list = element.getElementsByTagName(tagName);
if (list != null && list.getLength() > 0) {
NodeList subList = list.item(0).getChildNodes();
if (subList != null && subList.getLength() > 0) {
return subList.item(0).getNodeName();
}
}
return null;
}
}
这是xml文件
<Settings>
<debugLocation> test </debugLocation>
</Settings>
我以为我应该重新进行测试,但不是。