Я действительно плохо манипулирую XML, и мне нужна помощь. Вот пример моего файла XML:Получение подэлементов XML с Java
<?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>
Мне нужно напечатать вложенные элементы каждого и каждый ресурс агрегатор (идентификатор, типа, 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;
}
С этим я могу только получить идентификатор атрибута и не нужно. Мне нужно, чтобы все субэлементы были напечатаны, и он должен работать, даже если я добавляю подэлементы в свой XML-файл.
Как я могу это сделать?