我想問二級(節點)名稱爲例如失敗,condNotMeet。 我有一個XML文件,像這樣:如何使用Java在XML文件中獲取節點名稱?
<testcase classname="name1" name="description1" time="19.274">
<failure type="toBeMsg" message="error1" capture="_201601021755993.png">
</failure>
</testcase>
<testcase classname="name2" name="description2" time="19.274">
<failure type="toBeMsg" message="error2" capture="_20132143993.png">
</failure>
</testcase>
<testcase classname="name3" name="description3" time="19.274">
<condNotMeet type="toBeMsg" message="error3" capture="_2016.png">
</condNotMeet>
</testcase>
但是,如何索要「測試用例」 -s子節點的名稱,爲例:失敗,condNotMeet ...
我有這樣的代碼來啓動:
try {
File fXmlFile = new File("././full_1_tests.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
org.w3c.dom.Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("testcase");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
//System.out.println("\nCurrent Element :" + nNode.getNodeName() + " Node.ELEMENT_NODE::"+ Node.ELEMENT_NODE);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Test description: " + eElement.getAttribute("name") + " ");
// here it is the problem, how to get firstChildNode name???????? ...
System.out.println("|| Status: "+ nNode.getNodeName() ????); // Status: failure, condNotMee t
}
}
} catch (Exception e) {
System.out.println("Error : " + e);
}
目前是這樣的結果: 測試說明:說明1 ||狀態:null。 但是,我想要這個結果: 測試描述:description1 ||狀態:失敗 測試描述:description2 ||狀態:失敗 測試描述:description3 ||狀態:condNotMeet –
您發佈的xml格式不正確。所以我想知道,你的文檔是什麼... –
爲什麼不張貼xml corectly,因爲我忘了複製過去: <?xml version =「1.0」encoding =「UTF-8」?> –