- how to update XML data from java
- 1 Answer 1
- How to update xml files in java
- 4 Answers 4
- How to update xml files in java?
- Method 1: Using DOM Parser
- Java: How to Update XML Files Using DOM Parser
- Step 1: Import Required Packages
- Step 2: Load XML File
- Step 3: Get the Element to Update
- Step 4: Update the Element
- Step 5: Save the Updated XML File
- Method 2: Using SAX Parser
- Method 3: Using StAX Parser
how to update XML data from java
I want to change the text content of some field in xml using java. I used setTextContent() for this, but the xml file is not getting updated. here is my java code:
public static void main(String argv[]) < DisclosureTranslation dt=new DisclosureTranslation(); String filepath="E:\\Repository\\17Nov_demo\\file.xml"; dt.getHashmap(filepath); >public void getHashmap(String filepath) < try < DocumentBuilderFactory documentbuilderfactory=DocumentBuilderFactory.newInstance(); DocumentBuilder documentbuilder =documentbuilderfactory.newDocumentBuilder(); Document doc=documentbuilder.parse(filepath); XPath xPath = XPathFactory.newInstance().newXPath(); Element element=doc.getDocumentElement(); NodeList nodelist=(NodeList)xPath.evaluate("/DOCUMENT/ishobject/ishfields/ishfield[@name='FHPIDISCLOSURELEVEL']", doc.getDocumentElement(), XPathConstants.NODESET); System.out.println(nodelist.item(0).getTextContent()); String val=nodelist.item(0).getTextContent(); //String val="111"; HashMaphashmap=new HashMap(); hashmap.put("47406819852170807613486806879990", "public"); hashmap.put("222"," HP Internal"); String value=hashmap.get(val); nodelist.item(0).setTextContent(value); System.out.println(nodelist.item(0).getTextContent()); >
the last line is displaying what i want. But its not getting reflected in the xml file. How am i suppose to update my xml file? Thanks in advance! 🙂
1 Answer 1
Once you have updated the element from parsing the xml from the file path, update them to the same file using below method.
TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult streamResult = new StreamResult(new File(filePath)); transformer.transform(source, streamResult);
Saving the xml back to the file can also be achieved by using «Transformer API».
How to update xml files in java
I have a xml file call data.xml like the code below. The project can run from client side no problem and it can read the xml file. The problem I have now is I I want to write a function that can update the startdate and enddate. I have no idea how to get start. Help will be appreciated.
admin 12345 1 90 01/01/2013 06/01/2013 1110
public class main < public static void main(String[] args) < Calendar cal2 =null; try < //read the xml File data = new File("data.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(data); doc.getDocumentElement().normalize(); for (int i = 0; i < nodes.getLength(); i++) < Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) < Element element = (Element) node; username = getValue("username", element); startdate = getValue("startdate", element); enddate = getValue("enddate", element); >> date = startdate; Date date_int = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH).parse(date); cal2 = Calendar.getInstance(); cal2.setTime(date_int); //loop the child node to update the initial date for (int i = 0; i < nodes.getLength(); i++) < Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) < Element element = (Element) node; setValue("startdate", element , date_int.toString()); >> //write the content in xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("data.xml")); transformer.transform(source, result); > catch (Exception ex) < log.error(ex.getMessage()); ex.printStackTrace(); >> private static void setValue(String tag, Element element , String input)
4 Answers 4
Start by loading the XML file.
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); DocumentBuilder b = f.newDocumentBuilder(); Document doc = b.parse(new File("Data.xml"));
Now, there are a few ways to do this, but simply, you can use the xpath API to find the nodes you want and update their content
XPath xPath = XPathFactory.newInstance().newXPath(); Node startDateNode = (Node) xPath.compile("/data/startdate").evaluate(doc, XPathConstants.NODE); startDateNode.setTextContent("29/07/2015"); xPath = XPathFactory.newInstance().newXPath(); Node endDateNode = (Node) xPath.compile("/data/enddate").evaluate(doc, XPathConstants.NODE); endDateNode.setTextContent("29/07/2015");
Then save the Document back to the file.
Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.INDENT, "yes"); tf.setOutputProperty(OutputKeys.METHOD, "xml"); tf.setOutputProperty("indent-amount", "4"); DOMSource domSource = new DOMSource(doc); StreamResult sr = new StreamResult(new File("Data.xml")); tf.transform(domSource, sr);
Hi MadProgrammer, thank you for your answer, I have got the xml part working. Now what if I want to update the startdate’s month increase by one such as 29/07/2015, 29/8/2015, 20/10/2015 . something like this, how should I do that? Should I create a method to do it? Can you provide an example?
Hi, thank you for your respond, now I have updated my answer, how will you apply that into my code? I use Dom Parser instead of XPath. Thanks
Firstly there is an error in your XML you have extra tag . I have removed it. Now you have two options you could either use SAX or DOM . I would suggest DOM reason being that you can read full XML using DOM and for a small piece of XML like this it’s better choice.
import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; public class ModifyXMLFile < public static void main(String argv[]) < try < String filepath = "file.xml"; DocumentBuilderFactory docFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(filepath); // Get the root element Node data= doc.getFirstChild(); Node startdate = doc.getElementsByTagName("startdate").item(0); // I am not doing any thing with it just for showing you String currentStartdate = startdate.getNodeValue(); DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); Date today = Calendar.getInstance().getTime(); startdate.setTextContent(df.format(today)); // write the content into xml file TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File(filepath)); transformer.transform(source, result); System.out.println("Done"); >catch (ParserConfigurationException e) < // TODO Auto-generated catch block e.printStackTrace(); >catch (TransformerException e) < // TODO Auto-generated catch block e.printStackTrace(); >catch (SAXException e) < // TODO Auto-generated catch block e.printStackTrace(); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> >
admin 12345 1 90 29/07/2015 06/01/2013 1110
How to update xml files in java?
Updating XML files in Java is a common task when working with data stored in XML format. There are multiple approaches to updating an XML file in Java, and the best method to use depends on the specific requirements of the task at hand. In this article, we will cover several methods for updating XML files in Java, including using DOM, SAX, and StAX parsers.
Method 1: Using DOM Parser
Java: How to Update XML Files Using DOM Parser
Here is a step-by-step guide on how to update XML files using DOM Parser in Java:
Step 1: Import Required Packages
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import java.io.File;
Step 2: Load XML File
File xmlFile = new File("path/to/xml/file.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile);
Step 3: Get the Element to Update
NodeList nodeList = doc.getElementsByTagName("elementName"); Node node = nodeList.item(0); Element element = (Element) node;
Step 4: Update the Element
element.setAttribute("attributeName", "attributeValue"); element.getElementsByTagName("childElementName").item(0).setTextContent("newChildElementValue");
Step 5: Save the Updated XML File
TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("path/to/updated/xml/file.xml")); transformer.transform(source, result);
That’s it! This is how you can update XML files using DOM Parser in Java.
Method 2: Using SAX Parser
To update an XML file using SAX Parser in Java, you need to follow these steps:
- Create a SAX Parser instance.
- Implement the DefaultHandler class and override the necessary methods.
- Parse the XML file using the SAX Parser.
- Modify the XML content.
- Write the modified content back to the XML file.
import java.io.*; import javax.xml.parsers.*; import org.xml.sax.*; import org.xml.sax.helpers.*; public class UpdateXMLUsingSAXParser public static void main(String[] args) throws Exception // Step 1: Create a SAX Parser instance SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); // Step 2: Implement the DefaultHandler class and override the necessary methods DefaultHandler handler = new DefaultHandler() boolean isName = false; boolean isAge = false; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException if (qName.equalsIgnoreCase("name")) isName = true; > if (qName.equalsIgnoreCase("age")) isAge = true; > > public void characters(char[] ch, int start, int length) throws SAXException if (isName) String name = new String(ch, start, length); // Modify the name content name = name.toUpperCase(); System.out.println("Name : " + name); isName = false; > if (isAge) String age = new String(ch, start, length); // Modify the age content age = String.valueOf(Integer.parseInt(age) + 1); System.out.println("Age : " + age); isAge = false; > > >; // Step 3: Parse the XML file using the SAX Parser parser.parse(new File("input.xml"), handler); // Step 4: Modify the XML content (already done in Step 2) // Step 5: Write the modified content back to the XML file // (you can use any XML writer library to do this) > >
In this example, we have implemented the DefaultHandler class and overridden the startElement() and characters() methods to modify the content of the XML file. The startElement() method is called when the parser encounters a start tag, and the characters() method is called when the parser encounters the content between the start and end tags.
Note that this example only shows how to modify the content of the XML file using SAX Parser. To write the modified content back to the XML file, you can use any XML writer library such as DOM, JAXB, or XStream.
Method 3: Using StAX Parser
To update an XML file in Java using StAX parser, you can follow these steps:
- Create an instance of XMLInputFactory and XMLOutputFactory.
- Create an instance of XMLEventReader and XMLEventWriter using the input and output factories respectively.
- Read the XML file using the event reader and write it to a new file using the event writer.
- While writing the XML file, make the necessary changes using the event writer.
Here is an example code snippet that demonstrates how to update an XML file using StAX parser in Java:
import java.io.FileInputStream; import java.io.FileOutputStream; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.events.EndElement; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; public class UpdateXMLFile public static void main(String[] args) throws Exception // Step 1: Create input and output factories XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); // Step 2: Create event reader and writer XMLEventReader eventReader = inputFactory.createXMLEventReader(new FileInputStream("input.xml")); XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream("output.xml")); // Step 3: Read and write the XML file while (eventReader.hasNext()) XMLEvent event = eventReader.nextEvent(); // Write the event to the output file eventWriter.add(event); // Check if the event is a start or end element if (event.isStartElement()) StartElement startElement = event.asStartElement(); // Check if the start element is the element to be updated if (startElement.getName().getLocalPart().equals("element-to-update")) // Step 4: Make the necessary changes // Create a new attribute eventWriter.add(eventFactory.createAttribute("new-attribute", "new-value")); > > else if (event.isEndElement()) EndElement endElement = event.asEndElement(); // Check if the end element is the element to be updated if (endElement.getName().getLocalPart().equals("element-to-update")) // Step 4: Make the necessary changes // Create a new element eventWriter.add(eventFactory.createStartElement("", null, "new-element")); eventWriter.add(eventFactory.createEndElement("", null, "new-element")); > > > // Step 5: Close the event reader and writer eventReader.close(); eventWriter.close(); > >
In this example, we create an input factory and an output factory using the XMLInputFactory.newInstance() and XMLOutputFactory.newInstance() methods respectively. We then create an event reader and an event writer using these factories.
We read the XML file using the event reader and write it to a new file using the event writer. While writing the XML file, we check if the current event is a start or end element and if it is the element to be updated. If it is, we make the necessary changes using the event writer.
Finally, we close the event reader and writer using the close() method.
Note that this is just one way to update an XML file in Java using StAX parser. There are many other ways to do it depending on your specific requirements.