I am creating a simple java function to update/re-write the value of an xml file. I am able to pick the XML file from the system resource, after updating the file and re-writing, the value of the node never gets changes.
Here are my snippets:
String filePath = ABS_PATH + File.separator + "fields.xml";
File xmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
//update Element value
updateElementValue(doc);
//write the updated document to file or console
doc.getDocumentElement().normalize();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(ABS_PATH
+ File.separator + "fields.xml")); // updating/re-writing the same file
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(source, result);
System.out.println("XML file updated successfully");
} catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {
e1.printStackTrace();
}
//method to show the update element value
private static void updateElementValue(Document doc) {
NodeList employees = doc.getElementsByTagName("NO");
Element emp = null;
//loop for each
for (int i = 0; i < employees.getLength(); i++) {
emp = (Element)employees.item(i);
Node name = emp.getElementsByTagName("String").item(0).getFirstChild();
name.setNodeValue(name.getNodeValue().toUpperCase());
}
}
sample of the xml file
<Document xmlns="http://hello.com/schema/public/services/platform" Id="1">
<Fields>
<Field FieldName="NO">
<String>Demo</String>
</Field>
<Field FieldName="TYPE">
<String>Zada</String>
</Field>
</Fields>
who is motivated enough to assist