gpt4 book ai didi

java - 使用 XML 填充 JComboBox - 缺少一些内容

转载 作者:行者123 更新时间:2023-11-30 04:22:32 26 4
gpt4 key购买 nike

又是我。我有以下 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>

我想用每个资源(房屋、商业和工业)的 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 始终为空。我错过了什么?

谢谢;)

最佳答案

Element#getAttribute直接从Elements而不是从嵌套元素检索属性。您需要改为迭代 resource:

NodeList listaResources = raiz.getElementsByTagName("resource");

int tam = listaResources.getLength();
String[] vecResources = new String[tam];

for (int i = 0; i < tam; i++) {
Element elem = (Element) listaResources.item(i);
System.out.println(elem);
vecResources[i] = elem.getAttribute("id"); // change to id
}

关于java - 使用 XML 填充 JComboBox - 缺少一些内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16695903/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com