又是我。我有以下 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>
<resource id="Industry">
<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>
<agregator1 id="Microgrid">
<id>int</id>
<type>string</type>
</agregator1>
</agregatorsType1>
<soagregatorsType0>
<agregator0 id="VPP">
<id>int</id>
<type>string</type>
</agregator0>
</agregatorsType0>
</components>
我想用每个资源(House、Commerce 和 Industry)的 id 填充一个 JComboBox。
我有以下方法:
public static String[] readResourcesXML(String fileName) throws IOException, ClassNotFoundException, Exception {
//Gets XML
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = factory.newDocumentBuilder();
Document documento = docBuilder.parse(fileName);
//Searches all text
documento.getDocumentElement().normalize();
//Gets elements from xml
Element raiz = documento.getDocumentElement();
NodeList listaResources = raiz.getElementsByTagName("resources");
//Search all resources
int tam = listaResources.getLength();
String[] vecResources = new String[tam];
for (int i = 0; i < tam; i++) {
Element elem = (Element) listaResources.item(i);
vecResources[i] = elem.getAttribute("/resource/@id");
}
//returns an array with all the id's of the resources
return vecResources;
}
注意:字符串文件名具有以下值:“src\configs\features.xml”
问题是,JComboBox 总是空的。我错过了什么?
谢谢 ;)