gpt4 book ai didi

Java:XML dom 解析仅检索数组的 1 个元素

转载 作者:行者123 更新时间:2023-12-01 09:27:47 24 4
gpt4 key购买 nike

我有以下 XML(由 Web 服务提供)

<?xml version="1.0" encoding="UTF-8"?>
<itam>
<status>OK</status>
<data>
<item0>
<id>246</id>
<prefisso_quadrato>1</prefisso_quadrato>
<id_incontro_corrente />
<id_giornata>65</id_giornata>
<round>R1</round>
<tempo>120</tempo>
<punti_chong>0</punti_chong>
<punti_hong>0</punti_hong>
<amm_chong>0</amm_chong>
<amm_hong>0</amm_hong>
</item0>
<item1>
<id>247</id>
<prefisso_quadrato>2</prefisso_quadrato>
<id_incontro_corrente />
<id_giornata>65</id_giornata>
<round>R1</round>
<tempo>120</tempo>
<punti_chong>0</punti_chong>
<punti_hong>0</punti_hong>
<amm_chong>0</amm_chong>
<amm_hong>0</amm_hong>
</item1>
<item2>
<id>248</id>
<prefisso_quadrato>3</prefisso_quadrato>
<id_incontro_corrente />
<id_giornata>65</id_giornata>
<round>R1</round>
<tempo>120</tempo>
<punti_chong>0</punti_chong>
<punti_hong>0</punti_hong>
<amm_chong>0</amm_chong>
<amm_hong>0</amm_hong>
</item2>
</data>
</itam>

我正在尝试用JAVA解析它。我可以访问<status>以及<data>元素。但是当我尝试迭代<data>时items,我只能读取 1 个元素。这是代码:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document doc = builder.parse(is);
doc.getDocumentElement().normalize();
System.out.println(doc.getDocumentElement().getElementsByTagName("data").getLength());

OUTPUT: 1

我的想法类似于下面的代码,但它仅在第一个元素上运行(我可以读取其余元素属性,然后结束)。我该如何修复它?非常感谢

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document doc = builder.parse(is);
doc.getDocumentElement().normalize();
NodeList nodelist = doc.getDocumentElement().getElementsByTagName("data");
if(nodelist!=null){
for(int i=0; i<nodelist.getLength(); i++){
Element el = (Element) nodelist.item(i);
//use el to get data from it
}
}

最佳答案

错误是您正在查找 <data> 的列表元素,而你只有一个。解决方案可以是:

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document doc = builder.parse(is);
doc.getDocumentElement().normalize();
NodeList items = doc.getDocumentElement().getElementsByTagName("data").item(0).getChildNodes();

for(int i=0; i<items.getLength(); i++){
System.out.println(items.item(i).getNodeName());
}

祝你好运!

关于Java:XML dom 解析仅检索数组的 1 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39703915/

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