简体   繁体   中英

Java DOM parsing get only parent elements

I have the following xml:

<categories>
    <category id="1">
        <name>XML</name>
        <category id="2">
            <name>XPath</name>
        </category>
        <category id="3">
            <name>XML Schema</name>
        </category>
        <category id="4">
            <name>XSLT</name>
        </category>
        <category id="5">
            <name>XSL-FO</name>
        </category>
        <category id="6">
            <name>XQuery</name>
        </category>
    </category>
</categories>

I'm trying to parse this using DOM. I want to get the parent category and want to have output looking like the following:

Current element: category
Id: 1

I'm using the code below but am not getting the right output. How can I fix this?

NodeList xmlCategories = document.getElementsByTagName("category");
for (int i = 0; i < xmlCategories.getLength(); i++) {
    Node category = xmlCategories.item(i);
    if (category.hasChildNodes()) {
        System.out.println("\nCurrent element: " + category.getNodeName());
        if (category.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) category;

            System.out.println("Id: " + element.getAttribute("id"));
        }
    }
}

The output I'm getting is:

Current element: category
Id: 1

Current element: category
Id: 2

Current element: category
Id: 3

Current element: category
Id: 4

Current element: category
Id: 5

Current element: category
Id: 6
    NodeList xmlCategories = doc.getElementsByTagName("category");

    outer : for(int i=0;i<xmlCategories.getLength();i++){

        Node category = xmlCategories.item(i);

        if(category.getNodeType() == Node.ELEMENT_NODE){

            NodeList childrenCatgory = category.getChildNodes();

            inner : for(int j=0;j<childrenCatgory.getLength();j++){
                Node childCat = childrenCatgory.item(j);

                if(childCat.getNodeType() == Node.ELEMENT_NODE){

                    if(childCat.getNodeName().equals("category")){
                        Element catEle = (Element) category;
                        System.out.println("Current element: "+category.getNodeName());
                        System.out.println("Id: "+catEle.getAttribute("id"));

                        break outer;
                    }



                }
            }               

        }       

    }

I suppose this should do it.If a catagory element has a child called catagory, that's the parent and that's where I break out. The output is:

Current element: category

Id: 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM