我不明白为什么我的以下 xml 编写器没有保存到产品数组列表中。相反,我的程序没有向列表中添加任何内容,并且使用调试器我看到数组列表产品值始终为“size = 0”。我不确定为什么这个值没有改变,因为我试图将 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;
}