0
這是我的一次。 我有以下XML文件:使用XML填充JComboBox - 缺少一些東西
<?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>
,我想填充的JComboBox與每個資源(院,工商)的ID的。
我有以下方法:
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可總是空的。我錯過了什麼?
感謝)
解決了,非常感謝你 – SaintLike
順便說一句,如果我想打印的子元素? ID 類型 maxUsage etc 我需要做什麼? – SaintLike
您需要使用'getElementsByTagName'遍歷這些元素,類似於您已經完成的工作 – Reimeus