Append to XML file - java

I am writing a Java application with a method to save data to XML.
Here is my code:
private void SaveToXML(String strCity, String strDate, String strforecast, String strminDegrees, String FileName)
{
try
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Weather");
doc.appendChild(rootElement);
Element weatherElement = doc.createElement(strCity);
rootElement.appendChild(weatherElement);
Element dateElement = doc.createElement("Date");
weatherElement.appendChild(dateElement);
Attr attr = doc.createAttribute("id");
attr.setValue(strDate);
dateElement.setAttributeNode(attr);
Element forecast = doc.createElement("forecast");
forecast.appendChild(doc.createTextNode(strforecast));
dateElement.appendChild(forecast);
Element mindegrees = doc.createElement("mindegrees");
mindegrees.appendChild(doc.createTextNode(strminDegrees));
dateElement.appendChild(mindegrees);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(FileName));
transformer.transform(source, result);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
Method call:
SaveToXML("Auckland", "24-05-2013", "Fine", "10", "Test.xml");
Here is the output XML data:
<?xml version="1.0" encoding="UTF-8"?>
<Weather>
<Auckland>
<Date id="24-05-2013">
<forecast>Fine</forecast>
<mindegrees>10</mindegrees>
</Date>
</Auckland>
</Weather>
Can I please have some help to modify the code so that data is appended to the document in the correct element when the method is called.
E.g, If the method is called a second time with the City of Auckland, the weather details will be placed in the Auckland element. If a City is passed as a parameter that is not already in the document, a new element for that City will be created.
UPDATE2
This is my current code that performs an error:
private void SaveToXML(String strCity, String strDate, String strforecast, String strminDegrees, String FileName)
{
try
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
//Document doc = docBuilder.newDocument();
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(FileName));
Element rootElement = doc.createElement("Weather");
doc.appendChild(rootElement);
NodeList weatherNodes = rootElement.getElementsByTagName(strCity);// do we already have node?
Element weatherElement;
if(weatherNodes.getLength() > 0){ // if so reuse
weatherElement = (Element) weatherNodes.item(0);
System.out.println("Found");
}else { // else create
weatherElement = doc.createElement(strCity);
rootElement.appendChild(weatherElement);
}
Element dateElement = doc.createElement("Date");
weatherElement.appendChild(dateElement);
Attr attr = doc.createAttribute("id");
attr.setValue(strDate);
dateElement.setAttributeNode(attr);
Element forecast = doc.createElement("forecast");
forecast.appendChild(doc.createTextNode(strforecast));
dateElement.appendChild(forecast);
Element mindegrees = doc.createElement("mindegrees");
mindegrees.appendChild(doc.createTextNode(strminDegrees));
dateElement.appendChild(mindegrees);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(FileName));
transformer.transform(source, result);
} catch (Exception ex) {
ex.printStackTrace();
}
}
The above code generates this error at runtime:
[Fatal Error] Test.xml:1:177: The markup in the document following the root element must be well-formed.
org.xml.sax.SAXParseException: The markup in the document following the root element must be well-formed.
UPDATE3
Here is the code that is working:
private void SaveToXML(String strCity, String strDate, String strforecast, String strminDegrees, String FileName)
{
try
{
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc;
File file = new File(FileName);
if (!file.exists()) {
doc = docBuilder.newDocument();
doc.appendChild(doc.createElement("Weather"));
} else {
doc = docBuilder.parse(new File(FileName));
}
Element rootElement = doc.getDocumentElement();
Element weatherElement;
NodeList weatherNodes = doc.getDocumentElement().getElementsByTagName(strCity);
if (weatherNodes.getLength() > 0) {
weatherElement = (Element) weatherNodes.item(0);
} else {
weatherElement = doc.createElement(strCity);
rootElement.appendChild(weatherElement);
}
Element dateElement = doc.createElement("Date");
weatherElement.appendChild(dateElement);
Attr attr = doc.createAttribute("id");
attr.setValue(strDate);
dateElement.setAttributeNode(attr);
Element forecast = doc.createElement("forecast");
forecast.appendChild(doc.createTextNode(strforecast));
dateElement.appendChild(forecast);
Element mindegrees = doc.createElement("mindegrees");
mindegrees.appendChild(doc.createTextNode(strminDegrees));
dateElement.appendChild(mindegrees);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(FileName));
transformer.transform(source, result);
} catch (Exception ex) {
ex.printStackTrace();
}
}

To modify how you update the document structure for DOM,
modify
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Weather");
doc.appendChild(rootElement);
Element weatherElement = doc.createElement(strCity);
rootElement.appendChild(weatherElement);
to
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Weather");
doc.appendChild(rootElement);
NodeList weatherNodes = rootElement.getElementsByTagName(strCity);// do we already have node?
Element weatherElement;
if(weatherNodes.getLength() > 0){ // if so reuse
weatherElement = (Element) weatherNodes.item(0);
}else { // else create
weatherElement = doc.createElement(strCity);
rootElement.appendChild(weatherElement);
}
Be aware the DOM is really intended for small documents if this is going to get very large
you will need to look at something like STaX.

If XML file already exists you should parse it and update the city if it already exists or add otherwise. Then rewrite XML.
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc;
File file = new File(FileName);
if (!file.exists()) {
doc = docBuilder.newDocument();
doc.appendChild(doc.createElement("Weather"));
} else {
doc = docBuilder.parse(file);
}
Element rootElement = doc.getDocumentElement();
Element weatherElement = createWeatherElement(strCity, strDate, strforecast, strminDegrees, doc);
NodeList weatherNodes = doc.getDocumentElement().getElementsByTagName(strCity);
if (weatherNodes.getLength() > 0) {
rootElement.replaceChild(weatherElement, weatherNodes.item(0));
} else {
rootElement.appendChild(weatherElement);
}
Transformer transformer = transformerFactory.newTransformer();
...
private Element createWeatherElement(String strCity, String strDate, String strforecast, String strminDegrees, Document doc) {
Element rootElement = doc.getDocumentElement();
Element weatherElement = doc.createElement(strCity);
...
return weatherElement;
}

Related

Java XML How to - Use xpath to find and add/replace more children to a Nodelist in an XML file

I have an xml file (ToThis.xml) that i am updating with array variables. Am using Xpath to update to this xml file but i can only update the first array element. see below .
xml file (ToThis.xml) what i get
<?xml version="1.0" encoding="UTF-8"?><map xmlns="http://www.w3.org/2005/xpath-functions">
<string key="ankomstDato">2020-08-20</string>
<array key="planlagtAntallPerUndergruppe">
<map>
<number key="antall">67</number>
<string key="kode">SLAKTEGRIS</string>
</map>
</array>
</map>
xml file that i would like to get should be like this below
<?xml version="1.0" encoding="UTF-8"?><map xmlns="http://www.w3.org/2005/xpath-functions">
<string key="ankomstDato">2020-08-20</string>
<array key="planlagtAntallPerUndergruppe">
<map>
<number key="antall">67</number>
<string key="kode">SLAKTEGRIS</string>
</map>
<map>
<number key="antall">4</number>
<string key="kode">UNGSAU</string>
</map>
</array>
</map>
Below is portion of the code where it get me the first result. NOTE( The two array variable in real scenario are not hard coded they are assigned dynamically)
public void Write2XMLfile(){
XPathFactory xpathFact = XPathFactory.newInstance();
XPath xpath = xpathFact.newXPath();
try {
//
String filepath = "E:/utils/Tothis.xml";
//
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
planlagtAntallPerUndergruppe_antall_value[0] = "67";
planlagtAntallPerUndergruppe_kode_value[0] = "SLAKTEGRIS";
planlagtAntallPerUndergruppe_antall_value[1] = "4";
planlagtAntallPerUndergruppe_kode_value[1] = "UNGSAU";
//2. planlagtAntallPerUndergruppe **************************
System.out.println("\n This is second" );
Node planlagtAntallPerUndergruppe = (Node) xpath.evaluate("/map/array[#key='planlagtAntallPerUndergruppe']/*", doc, XPathConstants.NODE);
if(null != planlagtAntallPerUndergruppe) {
NodeList nodeList = planlagtAntallPerUndergruppe.getChildNodes();
for (int i = 0;null!=nodeList && i < nodeList.getLength(); i++) {
Node nod = nodeList.item(i);
if(nod.getNodeType() == Node.ELEMENT_NODE){
NodeList arrayElements_18 = (NodeList) xpath.evaluate("/map/array[#key='planlagtAntallPerUndergruppe']/*", doc, XPathConstants.NODESET);
//System.out.println("\n number of elements" + arrayElements_18.getLength());
for (int j = 0; j < arrayElements_18.getLength(); j++) {
//. antall
Node antall = (Node) xpath.evaluate("(/map/array/map/number[#key='antall'])[1]", doc, XPathConstants.NODE);
antall.setTextContent(planlagtAntallPerUndergruppe_antall_value[j]);
// end antall
//. kode
Node kode = (Node) xpath.evaluate("(/map/array/map/string[#key='kode'])[1]", doc, XPathConstants.NODE);
kode.setTextContent(planlagtAntallPerUndergruppe_kode_value[j]);
//System.out.println("\n\n antall: " + planlagtAntallPerUndergruppe_antall_value[j]);
// end kode
}
}
}
}
// end array planlagtAntallPerUndergruppe
// 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 Updating The Api_XML_Format.xml");
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
} catch (XPathExpressionException xee) {
xee.printStackTrace();
}
}
Xpath is purposely used to trace/read through an xml but cannot be used to modify an xml.
So, I changed my code from using XPath to using DOM Parser.
try
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
// Map root element
Element rootElement = doc.createElement("map");
doc.appendChild(rootElement);
//ROOT map
//1. ankomstDato
Element ankomstDato = doc.createElement("string");
Attr attrType_ankomstDato = doc.createAttribute("key");
attrType_ankomstDato.setValue("ankomstDato");
ankomstDato.setAttributeNode(attrType_ankomstDato);
ankomstDato.appendChild(doc.createTextNode(ankomstDato_value));
rootElement.appendChild(ankomstDato);
//. planlagtAntallPerUndergruppe
// planlagtAntallPerUndergruppe element
if (planlagtAntallPerUndergruppe_Count !=0){
Element planlagtAntallPerUndergruppe = doc.createElement("array");
rootElement.appendChild(planlagtAntallPerUndergruppe);
Attr attr = doc.createAttribute("key");
attr.setValue("planlagtAntallPerUndergruppe");
planlagtAntallPerUndergruppe.setAttributeNode(attr);
for (int i = 0; i < planlagtAntallPerUndergruppe_Count; i ++){
//to add "map" element
Element map1 = doc.createElement("map");
planlagtAntallPerUndergruppe.appendChild(map1);
// antall element
Element antall = doc.createElement("number");
Attr attrType = doc.createAttribute("key");
attrType.setValue("antall");
antall.setAttributeNode(attrType);
antall.appendChild(doc.createTextNode(planlagtAntallPerUndergruppe_antall_value[i]));
map1.appendChild(antall);
//kode element
Element kode = doc.createElement("string");
Attr attrType1 = doc.createAttribute("key");
attrType1.setValue("kode");
kode.setAttributeNode(attrType1);
kode.appendChild(doc.createTextNode(planlagtAntallPerUndergruppe_kode_value[i]));
map1.appendChild(kode);
}
}
//end planlagtAntallPerUndergruppe
// Write the content into XML file
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("E:/utils/students-new.xml"));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
// Beautify the format of the resulted XML
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(source, result);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
pass collected arrays into Write2XMLfile method as parameters
public void Write2XMLfile(String[] planlagtAntallPerUndergruppe_antall_value, String[] planlagtAntallPerUndergruppe_kode_value) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.newDocument();
Element rootElement = doc.createElement("map");
doc.appendChild(rootElement);
Element mainString = doc.createElement("string");
mainString.setAttribute("key", "ankomstDato");
rootElement.appendChild(mainString).setTextContent("2020-08-20");
Element array = doc.createElement("array");
array.setAttribute("key", "planlagtAntallPerUndergruppe");
rootElement.appendChild(array);
if(planlagtAntallPerUndergruppe_antall_value.length>0){
for (int i = 0; i < planlagtAntallPerUndergruppe_antall_value.length; i++) {
Element map = doc.createElement("map");
array.appendChild(map);
Element number = doc.createElement("number");
number.setAttribute("key", "antall");
map.appendChild(number).setTextContent(planlagtAntallPerUndergruppe_antall_value[i]);
Element string = doc.createElement("string");
string.setAttribute("key", "kode");
map.appendChild(string).setTextContent(planlagtAntallPerUndergruppe_kode_value[i]);
}
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(doc);
StreamResult output = new StreamResult(new File("output.xml"));
transformer.transform(source, output);
} catch (Exception e) {
e.printStackTrace();
}
}
output.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<map>
<string key="ankomstDato">2020-08-20</string>
<array key="planlagtAntallPerUndergruppe">
<map>
<number key="antall">67</number>
<string key="kode">SLAKTEGRIS</string>
</map>
<map>
<number key="antall">4</number>
<string key="kode">UNGSAU</string>
</map>
</array>
</map>

How to modify values of multiple XML tags?

I have been trying to modify values of more than one XML tag in java. So far I am able to get the values of the two nodes that I want to modify but while setting up values it always overrides the first one with the second one.
XML
<driver>
<BirthDate>1977-07-18</BirthDate>
<Age>40</Age>
<Gender>M</Gender>
<PrimaryResidence>OwnCondo</PrimaryResidence>
</driver>
I am trying to change Gender and PrimaryResidence tags.
Code
// Modifies multiple XML nodes
public static String changeCoreDiscountType(String reqXML) {
Document document = null;
String updatedXML = null;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(reqXML));
document = builder.parse(is);
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xPath.compile("/driver/Gender | /driver/PrimaryResidence");
NodeList nodeList = (NodeList) expression.evaluate(document,XPathConstants.NODESET);
for(int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
node.setTextContent("F");
node.setTextContent("OwnCondo");
String value = node.getTextContent();
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new StringWriter());
transformer.transform(source, result);
updatedXML = result.getWriter().toString();
} catch (Exception ex) {
ex.printStackTrace();
}
return updatedXML;
}
Any help is appreciated.
You need to check you are updating the correct node first, e.g.
for(int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if(node.getNodeName() == "Gender")
node.setTextContent("F");
if(node.getNodeName() == "PrimaryResidence")
node.setTextContent("OwnCondo");
}
Full Demo

How to update multiple nodes in xml in Java

I am trying to update multiple nodes in xml using nodelist. I am able to do it but i don't think my code is efficient. For updating two nodes I am repeating my code twice. I dont know how to loop it. I tried it from for loop, or tried making it an arraylist and everything but it is not working at all.
Here is my code:
String expressionDisclosure = "/DOCUMENT/ishobject/ishfields/ishfield[#name='FHPIDISCLOSURELEVEL']";
String expressionLanguage = "/DOCUMENT/ishobject/ishfields/ishfield[#name='DOC-LANGUAGE']";
String key = "";
String value = "";
try {
DocumentBuilderFactory documentbuilderfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentbuilder = documentbuilderfactory.newDocumentBuilder();
Document doc = documentbuilder.parse(filepath);
XPath xPath = XPathFactory.newInstance().newXPath();
Node updateNode = null;
NodeList nodelistLanguage = (NodeList) xPath.evaluate(expressionLanguage,
doc.getDocumentElement(), XPathConstants.NODESET);
NodeList nodelistDisclosure = (NodeList) xPath.evaluate(expressionDisclosure,
doc.getDocumentElement(), XPathConstants.NODESET);
key = nodelistLanguage.item(0).getTextContent();
if (key != null) {
value = getHashmap().get(key);
updateNode = nodelistLanguage.item(0);
updateNode.setTextContent(value);
}
key = nodelistDisclosure.item(0).getTextContent();
if (key != null) {
value = getHashmap().get(key);
updateNode = nodelistDisclosure.item(0);
updateNode.setTextContent(value);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult stream = new StreamResult(new File(filepath));
transformer.transform(source, stream);
} catch (Exception ex) {
ex.printStackTrace();
}
I am updating the node twice. Is this the proper way to do or can it be more efficient?

Retain escape character [" < etc..] while copying XML node - Java

I am creating target XML by copying source XML content. I am doing copy at node level.
Source XML has content with escape character which gets converted [$quot; to " etc...] while I create my target XML
Is there any way to retain original XML content.
Appreciate any help on this.
copyXmlFile("Workflow", "./Source.xml", "./Destination.xml");
private static void copyXmlFile(String xmlType, String objectSourceFile, String outfile) throws TransformerException {
//Get the DOM Builder Factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//Get the DOM Builder
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
//document contains the complete XML as a Tree.
try {
File xmlFileContent = new File(objectSourceFile);
Document document = builder.parse(new FileInputStream(xmlFileContent));
// root elements
Document documentOut = builder.newDocument();
Element rootElementOut = documentOut.createElement(xmlType);
rootElementOut.setAttribute("xmlns", "http://soap.sforce.com/2006/04/metadata");
documentOut.appendChild(rootElementOut);
NodeList nodeList = document.getDocumentElement().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
//Node copiedNode = documentOut.importNode(node, true);
//rootElementOut.appendChild(copiedNode);
rootElementOut.appendChild(documentOut.adoptNode(node.cloneNode(true)));
}
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(documentOut);
//StreamResult result = new StreamResult(new File(outfile));
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
//transformer.setOutputProperty(OutputKeys.METHOD, "xml");
//transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(source, result);
System.out.println("Escaped XML String in Java: " + writer.toString());
} catch (SAXException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }

updated xml data not updated in the xml file

i have made a method for updating my xml in the xml file by a using a GUI..
but when I update it everything seem to be working fine and the console is printing out the correct things.
But when I open the xml file and press refrah nothing is updated.
What is my problem?
public void updateObjType(String newTxt, int x) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
System.out.println("String value : " + newTxt);
System.out.println("Index value : " + x);
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse("xmlFiles/CoreDatamodel.xml");
XPath xPath = XPathFactory.newInstance().newXPath();
// Go thru the Object_types in the XML file and get item x.
NodeList nodeList = (NodeList) xPath.compile("//OBJECT_TYPE/text()")
.evaluate(xmlDocument, XPathConstants.NODESET);
// Set new NodeValue
nodeList.item(x).setNodeValue(newTxt);
String value = nodeList.item(x).getTextContent();
System.out.println(value);
}
this is the output from the console :
Original data : IF150Data
Incoming String value : Data
Index value : 4
updated data : Data
I solved it by using a transformer.
Full solution :
// Update the object type name from the object type list.
public void updateObjType(String newTxt, int x)
throws ParserConfigurationException, SAXException, IOException,
XPathExpressionException {
File file = new File("xmlFiles/CoreDatamodel.xml");
System.out.println("Incoming String value : " + newTxt);
System.out.println("Index value : " + x);
DocumentBuilderFactory builderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xPath.compile("//OBJECT_TYPE/text()")
.evaluate(xmlDocument, XPathConstants.NODESET);
// Set new NodeValue
nodeList.item(x).setNodeValue(newTxt);
// Save the new updates
try {
save(file, xmlDocument);
} catch (Exception e) {
e.printStackTrace();
}
}
And then the method I added :
public void save(File file, Document doc) throws Exception {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String s = writer.toString();
System.out.println(s);
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(s);
bufferedWriter.flush();
bufferedWriter.close();
}

Categories

Resources