1
我无法弄清楚为什么我的下面的xml编写器没有保存到产品数组列表中。相反,我的程序没有添加任何东西到列表中,并使用调试器,我发现数组列表的产品值始终是“size = 0”。我不知道为什么,我想从一个XML文件,这里的列表中添加元素这个值是不会改变的是什么我的代码,这样做看起来像:读取XML文件中的数据并将其保存到数组
private static ArrayList<Product> readProducts()
{
ArrayList<Product> products = new ArrayList<>();
Product p = null;
XMLInputFactory inputFactory = XMLInputFactory.newFactory();
try
{
//create a stream reader object
FileReader fileReader = new FileReader("products.xml");
XMLStreamReader reader = inputFactory.createXMLStreamReader(fileReader);
//read XML file
while (reader.hasNext())
{
int eventType = reader.getEventType();
switch (eventType)
{
case XMLStreamConstants.START_ELEMENT :
String elementName = reader.getLocalName();
//get the product and its code
if (elementName.equals("Product"))
{
p = new Product();
String code = reader.getAttributeValue(0);
p.setCode(code);
}
// get the product description
if (elementName.equals("Description"))
{
String description = reader.getElementText();
p.setDescription(description);
}
// get the product price
if (elementName.equals("Price"))
{
String priceS = reader.getElementText();
double price = Double.parseDouble(priceS);
p.setPrice(price);
}
break;
case XMLStreamConstants.END_ELEMENT :
elementName = reader.getLocalName();
if(elementName.equals("product"))
{
products.add(p);
}
break;
}
reader.next();
}
}
catch (IOException | XMLStreamException e)
{
System.out.println(e);
}
return products;
}
'“产品”'不等于'“产品”'... – jlordo 2013-05-10 05:37:53
+1,jlordo ...... – 2013-05-10 05:39:55
这解决了这个问题非常感谢,我不知道为什么我从来没有看到该p我一直在使用googling的东西,并在过去的一小时内检查过我的代码,并且这样简单的修复 – 2013-05-10 05:42:57