簡體   English   中英

使用Java獲取XML子元素

[英]Obtaining XML sub-elements with Java

我操作XML真的很糟糕,我需要一些幫助。 這是我的XML文件的示例:

<?xml version="1.0"?>
<components>
    <resources>
        <resource id="House">
            <id>int</id>
            <type>string</type>
            <maxUsage>float</maxUsage>
            <minUsage>float</minUsage>
            <averageUsage>float</averageUsage>
        </resource>
        <resource id="Commerce">
            <id>int</id>
            <type>string</type>
            <maxUsage>float</maxUsage>
            <minUsage>float</minUsage>
            <averageUsage>float</averageUsage>
        </resource>
    </resources>
    <agregatorsType1>
        <agregator1 id="CSP">
            <id>int</id>
            <type>string</type>
        </agregator1>
    </agregatorsType1>
    <soagregatorsType0>
        <agregator0 id="VPP">
            <id>int</id>
            <type>string</type>
        </agregator0>
    </agregatorsType0>
</components>

我需要打印每個資源的子元素和每個agregator(id,type,maxUsage等)。

這是我的方法:

public static Document createXMLDocument() throws IOException, Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = factory.newDocumentBuilder();
    Document documento = docBuilder.parse(filepath);
    documento.getDocumentElement().normalize();
    return documento;
}

public static String[] readSubElementsXML() throws IOException, Exception 
{   

    Document documento = createXMLDocument();

    //gets XML elements 
    Element root = documento.getDocumentElement();
    NodeList nListR = root.getElementsByTagName("resource");
    NodeList nListA1 = root.getElementsByTagName("agregator1");
    NodeList nListA0 = root.getElementsByTagName("agregator0");

    ArrayList<Node> allNodes = appendNodeLists(nListR, nListA1, nListA0); //this method merges the 3 NodeLists into one ArrayList

    int tam = allNodes.size();
    String[] vec = new String[tam];

    for (int i = 0; i < tam; i++) {
        Element elem = (Element) allNodes.get(i);               
        vec[i] =  elem.getAttribute("id");
        System.out.println(""+vec[i]);
    }
    return vec;
}

有了這個,我只能得到屬性id,我不需要它。 我需要打印所有子元素,即使我將子元素添加到XML文件中也必須工作。

我怎樣才能做到這一點?

根據需要使用elem.getChildNodes()。這將為您提供NodeList

Element是Node的子類。 請參閱Node#getChildNodes() javadoc。

包含此節點的所有子節點的NodeList。 如果沒有子節點,則這是一個不包含節點的NodeList。

然后,您可以迭代子節點,如

    NodeList childNodes = elem.getChildNodes();
    int childCount = childNodes.getLength();
    Node childNode;
    for (int i = 0; i < childCount; i++) {
        childNode = childNodes.item(i);
        // do things with the node
    }

我建議你使用StAX,它是一個非常容易使用的XML,它設計精美,可以讀取XML和編寫XML。

“StAX是一種標准的XML處理API,允許您從應用程序流式傳輸XML數據”----來自StAX主頁

使用StAX解析所有內容的示例是:

try {
    for (int i = 0 ; i < count ; i++) {
        // pass the file name.. all relative entity
        // references will be resolved against this as
        // base URI.
        XMLStreamReader xmlr =
            xmlif.createXMLStreamReader(filename,
                new FileInputStream(filename));
        // when XMLStreamReader is created, it is positioned
        // at START_DOCUMENT event.
        int eventType = xmlr.getEventType();
        printEventType(eventType);
        printStartDocument(xmlr);
        // check if there are more events in the input stream
        while(xmlr.hasNext()) {
            eventType = xmlr.next();
            printEventType(eventType);
            // these functions print the information about
            // the particular event by calling the relevant
            // function
            printStartElement(xmlr);
            printEndElement(xmlr);
            printText(xmlr);
            printPIData(xmlr);
            printComment(xmlr);
        }
    }
}
----from http://docs.oracle.com/

暫無
暫無

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

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