Question

I can't figure out why my following xml writer is not saving to the products array list. Instead my program is not adding anything to the list and using a debugger I see that the array list products value is always "size = 0". I'm not sure why this value is not changing as I am trying to add elements from an XML file to the list here is what my code to do that looks like:

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;
    }
Was it helpful?

Solution

If your opening tag has the name Product, than the corresponding closing tag must be Product for it to be valid xml. Therefor you need to change

if(elementName.equals("product"))

to

if(elementName.equals("Product"))
                       ^

if you want to see your desired behaviour.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top