想實現一個讀取配置文件來得到想要的數據,寫了一個demo.
package Test;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
public class Demo1 {
//讀取.xml配置文件
public static void main(String[] args){
try{
//創建DOM解析器工廠
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//調用DOM解析器工廠的newDocumentBuilder()方法得到DOM解析器對象
DocumentBuilder db = dbf.newDocumentBuilder();
//調用DOM解析器對象parse(String url)方法得到document對象
Document doc = db.parse("src\\ProcessConfig.xml");
//調用Document對象的getElementByTagName(String tagname)方法得到NodeList對象
NodeList n1 = doc.getElementsByTagName("VALUE");
/*
遍歷xml中的元素
*/
for(int i=0;i<n1.getLength();i++) {
System.out.println("進程中文名:" + doc.getElementsByTagName("CNAME").item(i).getFirstChild().getNodeValue());
System.out.println("進程英文名:" + doc.getElementsByTagName("ENAME").item(i).getFirstChild().getNodeValue());
System.out.println("進程路徑:" + doc.getElementsByTagName("PATH").item(i).getFirstChild().getNodeValue());
}
}catch (Exception e){
e.printStackTrace();
}
}
}
.xml的配置文件。
<?xml version="1.0" encoding="GBK" ?>
<RESULT>
<VALUE>
<CNAME>谷歌瀏覽器</CNAME>
<ENAME>chrome.exe</ENAME>
<PATH>C:\\Program File \\chrome.exe</PATH>
</VALUE>
<VALUE>
<CNAME>IDEA編譯器</CNAME>
<ENAME>idea64.exe</ENAME>
<PATH>F:\\JetBrains\\IntelliJ IDEA 2018.3.6\\bin\\idea64.exe</PATH>
</VALUE>
</RESULT>
程序的運行結果:
進程中文名:谷歌瀏覽器
進程英文名:chrome.exe
進程路徑:C:\\Program File \\chrome.exe
進程中文名:IDEA編譯器
進程英文名:idea64.exe
進程路徑:F:\\JetBrains\\IntelliJ IDEA 2018.3.6\\bin\\idea64.exe