用Java获取XML子元素

用Java获取XML子元素,java,xml,xml-parsing,Java,Xml,Xml Parsing,我真的很不擅长处理XML,我需要一些帮助。 以下是我的XML文件示例: <?xml version="1.0"?> <components> <resources> <resource id="House"> <id>int</id> <type>string</type> <maxUsage>

我真的很不擅长处理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>

int
一串
浮动
浮动
浮动
int
一串
浮动
浮动
浮动
int
一串
int
一串
我需要打印每个资源和每个agregator的子元素(id、type、maxuse等)

以下是我的方法:

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;
}
public static Document createXMLDocument()抛出IOException,Exception{
DocumentBuilderFactory工厂=DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder=factory.newDocumentBuilder();
Document documento=docBuilder.parse(文件路径);
documento.getDocumentElement().normalize();
返回文件o;
}
公共静态字符串[]readSubElementsXML()引发IOException,Exception
{   
Document documento=createXMLDocument();
//获取XML元素
元素根=documento.getDocumentElement();
NodeList nListR=root.getElementsByTagName(“资源”);
NodeList nListA1=root.getElementsByTagName(“agregator1”);
NodeList nListA0=root.getElementsByTagName(“agregator0”);
ArrayList allNodes=AppendNodeList(nListR,nListA1,nListA0);//此方法将3个节点列表合并到一个ArrayList中
int tam=allNodes.size();
字符串[]向量=新字符串[tam];
for(int i=0;i
有了这个,我只能得到属性id,我不需要它。我需要打印所有子元素,即使我将子元素添加到XML文件中,它也必须工作


我该怎么做呢?

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

元素是Node的子类。见javadoc

包含此节点的所有子节点的节点列表。如果没有子节点,则该节点列表不包含任何节点

然后,您可以在子节点上进行迭代,如

    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
    }
nodelistchildnodes=elem.getChildNodes();
int childCount=childNodes.getLength();
节点子节点;
for(int i=0;i
我建议您使用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/
试试看{
for(int i=0;i