我正在根据节点的元素解析rss feed并将其设置为bean对象。后来,我需要将它存储在bean的ArrayList中。看起来我在设置bean值时做错了,并且还将它添加到了Bean的ArrayList中。 这是我的代码:
public static void main(String arg[]) {
ArrayList<RssBean> list = new ArrayList<RssBean>();
RssBean bean = new RssBean(null, null, null);
String xmlRecords =
"<rss>" +"<channel>"+
" <item>" +
" <title>John</title>" +
" <description> Desc1 </description>"+
" </item>" +
" <item>" +
" <title>Sara</title>" +
" <description> Desc2 </description>"+
" </item>" + "</channel>"+
"</rss>";
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("item");
// iterate the items
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("title");
Element line = (Element) title.item(0);
bean.setTitle(getCharacterDataFromElement(line));
NodeList description = element.getElementsByTagName("description");
line = (Element) description.item(0);
bean.setDescription(getCharacterDataFromElement(line));
list.add(bean);
}
//print list values
ListIterator<RssBean> iter = list.listIterator() ;
while(iter.hasNext())
{
RssBean result = (RssBean)iter.next();
System.out.println(result);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
当我打印出列表值时,我得到 - 列出值======&gt; [RssBean @ 450cceb3,RssBean @ 450cceb3]这是不期望的。我需要将实际值存储在bean的数组列表中。 ArrayList显示对象而不是存储的实际值。你能纠正我的代码吗?
答案 0 :(得分:1)
ArrayList不复制存储值,它只存储对添加对象的引用。因此,在您的代码中,您将一个bean实例放置三次。
如果问题仅在于复制打印项目中的值,则应更改代码以在每次循环迭代时创建新的bean实例
for (int i = 0; i < nodes.getLength(); i++) {
RssBean bean = new RssBean(null, null, null);
Element element = (Element) nodes.item(i);
// ...
list.add(bean)
}
但是如果你在打印bean字段时遇到问题,你应该在RssBean类中重写toString()方法
@Override
public String toString() {
return "Bean Values ======>" + getTitle + "&&" + getDesc();
}
答案 1 :(得分:1)
您正在列表中添加对象,这就是打印对象“RssBean @ 450cceb3”的原因。
值存储在Objects中,您可以通过覆盖RssBean类中的toString()方法来打印它。
更新您的RssBean,如:
public class RssBean {
String title;
String description;
String value;
public RssBean(String title, String description, String value) {
this.title = title;
this.description = description;
this.value = value;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append("Title: " + title);
result.append("Description: " + description);
result.append("Value: " + value);
return result.toString();
}
}