簡體   English   中英

獲取節點 XML Java 的所有子節點

[英]Get all child nodes of a node XML Java

我正在讀取 XML 文件並顯示文件的輸出。

但問題是,當一個節點有很多子節點時,會發生這種情況:

---------character
---------id
------------>148
---------name
------------>Arya Stark
---------gender
------------>Female
---------culture
------------>Northmen
---------born
------------>In 289 AC, at Winterfell
---------died
---------alive
------------>TRUE
---------titles
---------title
------------>Princess
---------aliases
---------alias
------------>Arya Horseface
---------alias
------------>Arya Underfoot
---------alias
------------>Arry
---------alias
------------>Lumpyface
---------alias
------------>Lumpyhead
---------alias
------------>Stickboy
---------alias
------------>Weasel
---------alias
------------>Nymeria
---------alias
------------>Squan
---------alias
------------>Saltb
---------alias
------------>Cat of the Canaly
---------alias
------------>Bets
---------alias
------------>The Blind Girh
---------alias
------------>The Ugly Little Girl
---------alias
------------>Mercedenl
---------alias
------------>Mercye

如您所見,別名有很多別名,我想同時輸出它們。

這是我的代碼:

public class JavaApplication20 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws ParserConfigurationException, org.xml.sax.SAXException, IOException {

        String path = "got.xml";

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        org.w3c.dom.Document document = builder.parse(path);

        document.getDocumentElement().normalize();

        iterateNodes(document.getDocumentElement());

    }

    private static void iterateNodes(Node node) {

        NodeList nodeList = node.getChildNodes();

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node currentode = nodeList.item(i);

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

                System.out.print("---------");
                System.out.println(currentode.getNodeName().trim());

                Element element = (Element) currentode;
                iterateNodes(element);
            } else if (!nodeList.item(i).getTextContent().trim().equals("")) {
                System.out.println("------------>" + nodeList.item(i).getTextContent().trim());

            }

        }

    }

}

我試圖檢測一個節點何時有許多子節點,但我不知道。

提前致謝!

我已經解決了,這是一個糟糕的解決方案,但解決了問題!

我創建了一個存儲節點名的字符串,如果下一個節點與字符串 var 同名,則 id 不打印名稱

   if(!anterior.equals(currentode.getNodeName().trim())){
         System.out.print("---------");
            System.out.println(currentode.getNodeName().trim());
     } 
            
            
            anterior=currentode.getNodeName().trim();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM