选择性XML阅读

时间:2017-01-13 18:30:12

标签: java

我可以按照以下代码阅读XML。

这是一个示例输入文件:

<explain>
    <Query-Text>
    </Query-Text>
    <Plan>
        <Node-Type></Node-Type>
        <Startup-Cost></Startup-Cost>
        <Total-Cost></Total-Cost>
        <Actual-Total-Time></Actual-Total-Time>
        <Actual-Rows></Actual-Rows>
        <Actual-Loops></Actual-Loops>
        <Plans>
                <Plan>
                        <Node-Type></Node-Type>
                        <Startup-Cost></Startup-Cost>
                        <Total-Cost></Total-Cost>
                        <Actual-Rows></Actual-Rows>
                        <Actual-Loops></Actual-Loops>
                </Plan>
          </Plans>
    </Plan>
</explain>

我只需要读取第一个PLAN: "Total-Cost"标记中的标记"Actual-Total-Time"PLAN信息。问题是内部层次结构中有PLAN,这是正在阅读。我怎么能只阅读第一个PLAN标签,而不是那些我不感兴趣的标签? 这是我的代码:

File fXmlFile = new File("/home/user1/Downloads/LOGT1.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName("Plan");

for (int temp = 0; temp < nList.getLength(); temp++) {
    //SAMPLE Node nNode = nList.item(temp);
    System.out.println("\nCurrent Element :" + nNode.getNodeName());                            
    if (nNode.getNodeType() == Node.ELEMENT_NODE) {             Element eElement = (Element) nNode;
        System.out.println("Total Cost query: " + eElement.getElementsByTagName("Total-Cost").item(0).getTextContent());
        System.out.println("Actual Total Time query:" + eElement.getElementsByTagName("Actual-Total-Time").item(0).getTextContent());
        }

此代码不会引发任何错误,但不符合所需的行为。

2 个答案:

答案 0 :(得分:0)

我认为你正在寻找这样的东西:

for (int temp = 0; temp < nList.getLength(); temp++) { //SAMPLE       
    Node nNode = nList.item(temp);
    if (nNode.getParent().getNodeName().equals("Plans")) {
        continue;
    }
    System.out.println("\nCurrent Element :" + nNode.getNodeName());
    ...
}

答案 1 :(得分:0)

只需使用 XPath 即可获取值。下面的代码将为您提供所需内容:

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

String Total_Cost = xPath.evaluate("//explain/Plan/Total-Cost/text()", doc).trim();
String Actual_Total_Time = xPath.evaluate("//explain/Plan/Actual-Total-Time/text()", doc).trim();