java - Reading data in an XML file and saving it to an array -


i can't figure out why following xml writer not saving products array list. instead program not adding list , using debugger see array list products value "size = 0". i'm not sure why value not changing trying add elements xml file list here code looks like:

private static arraylist<product> readproducts() {     arraylist<product> products = new arraylist<>();     product p = null;     xmlinputfactory inputfactory = xmlinputfactory.newfactory();     try     {         //create 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 product , code                   if (elementname.equals("product"))                   {                      p = new product();                      string code = reader.getattributevalue(0);                      p.setcode(code);                   }                      // product description                   if (elementname.equals("description"))                   {                      string description = reader.getelementtext();                      p.setdescription(description);                   }                       // 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;     } 

if opening tag has name product, corresponding closing tag must product valid xml. therefor need change

if(elementname.equals("product")) 

to

if(elementname.equals("product"))                        ^ 

if want see desired behaviour.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -