如何使用Java在XML文件中获取节点名称?

时间:2016-02-01 14:03:13

标签: java xml

我想问第二级(节点)名称例如失败,condNotMeet。 我有一个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="_20160123412.png">
   </condNotMeet>
</testcase>

但是,如何询问“testcase”-s子节点名称,例如:failure,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);
        }

2 个答案:

答案 0 :(得分:1)

获得testcase元素的元素节点后:

Element eElement = (Element) nNode;
System.out.println("Test description: " + eElement.getAttribute("name") + " ");

您可以获取该元素的子元素并遍历此列表:

NodeList children = eElement.getChildNodes();
for (...

或者您可以获得第一个子元素(如果这是唯一感兴趣的元素):

Element child = (Element)eElement.getFirstChild();

(自从您对文档进行规范化后,这应该会成功)。

答案 1 :(得分:1)

如果您希望直接获得第二级节点,则需要condNotMeet

所以你可以使用下面的代码:

 XPath xPath = (XPath) XPathFactory.newInstance().newXPath();


 String condNotMeetExpression = "//testcase/condNotMeet";
 Node node = (Node) xPath.compile(condNotMeetExpression).evaluate(doc,
    XPathConstants.NODE);

这里你将获得condNotMeet节点。也适用于其他节点。

String failure Expression = "//testcase/failure";
Node node = (Node) xPath.compile(failureExpression).evaluate(doc,
        XPathConstants.NODE);

                   OR

如果您想要所有失败节点的列表,那么您可以使用以下代码:

String failure Expression = "//testcase/failure";
NodeList list= (NodeList)xPath.compile(failureExpression).evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < list.getLength(); i++) {
    Node node = list.item(i);
    //further code foe getting attributes
}