简体   繁体   中英

Obtaining XML sub-elements with Java

I'm really bad manipulating XML and I need some help. Here's a sample of my XML file:

<?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>

I need to print the sub-elements of each resourse and each agregator (id, type, maxUsage, etc).

Here are my methods:

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;
}

With this I can only get the attribute id and I don't need it. I need to get all sub-elements printed and it has to work even if I add sub-elements to my XML file.

How can I do that?

根据需要使用elem.getChildNodes()。这将为您提供NodeList

Element is a subclass of Node. See Node#getChildNodes() javadoc.

A NodeList that contains all children of this node. If there are no children, this is a NodeList containing no nodes.

You are then able to iterate over the child nodes like

    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
    }

I recommend you to use StAX, it is a very easy to use XML and it is beautifully designed for reading XML and writing XML.

"StAX is a standard XML processing API that allows you to stream XML data from and to your application" ---- From StAX Home Page

An example to parse everything with StAX is:

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/

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