XML : Updating XML file

I have came up with a function to update a node element in the XML. My sample XML look like this -

  <MYXML>    <Product id="S-001">      <Name>Samsung</Name>      <Location>Annex-S1</Location>      <Count>1000</Count>    </Product>    <Product id="T-001">      <Name>Toshiba</Name>      <Location>Annex-T1</Location>      <Count>2000</Count>    </Product>  </MYXML>    

User will input a Product ID and Count, so i need to find the matching product id and then change it's count.

Below is the function that i came up with to update the XML count value.

  public void updateProductData(String count, String productID) {              File xmlFile = new File(xmlPathName);              DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();              DocumentBuilder dBuilder;                try {                  dBuilder = dbFactory.newDocumentBuilder();                  Document doc = dBuilder.parse(xmlFile);                  doc.getDocumentElement().normalize();                  NodeList products = doc.getElementsByTagName("Product");                  Element elem = null;                  //loop for each product                  for(int i=0; i < products.getLength(); i++) {                      elem = (Element) products.item(i);                      if (elem.getNodeType() == Node.ELEMENT_NODE) {                            Element eElement = (Element) elem;                            if (eElement.getAttribute("id").equals(productID)) {                              org.w3c.dom.Node name = elem.getElementsByTagName("Count").item(0).getFirstChild();                              name.setNodeValue(count);                          }                      }                  }                      TransformerFactory transformerFactory = TransformerFactory.newInstance();                  Transformer transformer = transformerFactory.newTransformer();                  DOMSource source = new DOMSource(doc);                  StreamResult result = new StreamResult(new File(xmlPathName));                  transformer.transform(source, result);                } catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {                  e1.printStackTrace();              }          }    

Now what happens is, if i pass "S-001" as product id and 250 as count, then this function will correctly change the count value for the S-001 product id. After changing the count value for S-001, if i pass product id as "T-001" and count as 500, then it will change the count value for T-001 but it will revert the count value of S-001 to 1000, which was the original one.

For some reason, the value that's not changed get's reverted back to the original one when the XML file was initially created.

Any ideas?

No comments:

Post a Comment