我正在根据节点的元素解析 rss 提要并将其设置为 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 "?";
}
当我打印出列表值时,我得到 - List Values ======>[RssBean@450cceb3, RssBean@450cceb3] 这不是预期的。我需要将实际值存储在 bean 的数组列表中。ArrayList 显示对象而不是存储的实际值。你能更正我的代码吗?