gpt4 book ai didi

java - 我现在正在使用 SAX 进行解析

转载 作者:行者123 更新时间:2023-12-01 15:17:42 24 4
gpt4 key购买 nike

我正在尝试使用 SAX 解析 XML 文档。 XML 文档如下所示:

<users>
<row Id="-1" DisplayName="Apple">
<row Id="1" DisplayName="Banana">
<row Id="2" DisplayName="Orange">
</users>

这是我的解析器类的摘录,它负责解析 row 元素:

class SAXParser extends DefaultHandler {

static int i = 0;
ArrayList<ArrayList<String>> ar = new ArrayList<ArrayList<String>>();
ArrayList<String> id = new ArrayList<String>();

public void startElement(String uri, String localName,
String qName, Attributes atts) {

if (qName.equals("row")) {
int idx = 0;
id.add(idx, atts.getValue(0));
idx++;
id.add(idx, atts.getValue(3));
ar.add(i, id);
i++;
//idx = 0;
}
}

}

如果我运行该程序,我会在 ar 属性中得到以下结果,这不是我想要的:

[2,Orange,1,Banana,-1,Apple], [2,Orange,1,Banana,-1,Apple],
[2,Orange,1,Banana,-1,Apple], [2,Orange,1,Banana,-1,Apple]

我想要的是在 ar 属性中包含 IdDisplayName 对,如下所示:

[-1, Apple], [1, Banana], [2, Orange]

我做错了什么?我怎样才能达到预期的结果?

最佳答案

问题是您仅实例化 id 列表一次,因此该列表将包含所有行的所有元素(标识符和显示名称)。

您必须为每一对创建一个新的ArrayList:

class SAXParser extends DefaultHandler 
{
static int i = 0;
ArrayList<ArrayList<String>> ar = new ArrayList<ArrayList<String>>();
// ***** Instead of creating the list here *****
// ArrayList<String> id = new ArrayList<String>();

public void startElement(String uri, String localName, String qName, Attributes atts) {
if (qName.equals("row")) {
// ***** Move that line here: *****
ArrayList<String> id = new ArrayList<String>();

int idx = 0;
id.add(idx, atts.getValue(0));
idx++;
id.add(idx, atts.getValue(3));
ar.add(i, id);
i++;
//idx = 0;
}
}
}

请注意,如果您按顺序向列表中添加项目,则不必为每次添加指定索引,元素将按添加顺序放置。因此您的代码可以进一步简化:

public void startElement(String uri, String localName, String qName, Attributes atts) {
if (qName.equals("row")) {
ArrayList<String> id = new ArrayList<String>();
id.add(atts.getValue(0));
id.add(atts.getValue(3));
ar.add(id);
}
}

关于java - 我现在正在使用 SAX 进行解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11406862/

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