简体   繁体   English

使用Java获取XML子元素

[英]Obtaining XML sub-elements with Java

I'm really bad manipulating XML and I need some help. 我操作XML真的很糟糕,我需要一些帮助。 Here's a sample of my XML file: 这是我的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>

I need to print the sub-elements of each resourse and each agregator (id, type, maxUsage, etc). 我需要打印每个资源的子元素和每个agregator(id,type,maxUsage等)。

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. 有了这个,我只能得到属性id,我不需要它。 I need to get all sub-elements printed and it has to work even if I add sub-elements to my XML file. 我需要打印所有子元素,即使我将子元素添加到XML文件中也必须工作。

How can I do that? 我怎样才能做到这一点?

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

Element is a subclass of Node. Element是Node的子类。 See Node#getChildNodes() javadoc. 请参阅Node#getChildNodes() javadoc。

A NodeList that contains all children of this node. 包含此节点的所有子节点的NodeList。 If there are no children, this is a NodeList containing no nodes. 如果没有子节点,则这是一个不包含节点的NodeList。

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,它是一个非常容易使用的XML,它设计精美,可以读取XML和编写XML。

"StAX is a standard XML processing API that allows you to stream XML data from and to your application" ---- From StAX Home Page “StAX是一种标准的XML处理API,允许您从应用程序流式传输XML数据”----来自StAX主页

An example to parse everything with StAX is: 使用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