How to save parsed and changed DOM document in xml file?
Something like this works:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult(new File("output.xml"));
Source input = new DOMSource(myDocument);
transformer.transform(input, output);
How do you save DOM Document in Java?
Here is the sample code for updating an XML file
try
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filePath);
Node rootNode = doc.getFirstChild();//for getting the root node
String expersion="books/author";//x-path experssion
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile(expersion);
Node updateNode=null;
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
updateNode=nodes.item(0);
updateNode.appendChild(doc.createCDATASection("new value"));
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult streamResult = new StreamResult(new File(filePath));
transformer.transform(source, streamResult);
}
catch (Exception e) {
e.printStackTrace();
}
python: how to save physically the xml file after change
You can simply open the file and write the output of xmldoc.toxml()
to it. Example -
...
with open('country.xml','w') as f:
f.write(xmldoc.toxml())
Edited XML content not changing after save to File
You are updating the Element node, and that operation has no effect. Besides, I think the following is more robust, since it wll iterate over all text nodes, and not just the first.
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
Node child = currentNode.getFirstChild();
while(child != null) {
if (child.getNodeType() == Node.TEXT_NODE) {
child.setTextContent(StringEscapeUtils.escapeXml(child.getNodeValue()));
}
child = child.getNextSibling();
}
}
}
Writing Out a DOM as an XML File
You really just have to transform the DOM to your file.
Example
// Create DOM
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element root = document.createElement("Root");
document.appendChild(root);
Element foo = document.createElement("Foo");
foo.appendChild(document.createTextNode("Bar"));
root.appendChild(foo);
You can save that DOM to a file like this:
// Write DOM to file as XML
File xmlFile = new File("/path/to/file.xml");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(document), new StreamResult(xmlFile));
You can also just print the DOM like this:
// Print DOM as XML
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(new DOMSource(document), new StreamResult(System.out));
Output
<?xml version="1.0" encoding="UTF-8" standalone="no"?><Root><Foo>Bar</Foo></Root>
If you want the XML formatted:
// Print DOM as formatted XML
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(new DOMSource(document), new StreamResult(System.out));
Output
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Root>
<Foo>Bar</Foo>
</Root>
Read/write XML file preserving original attribute order
Attribute order is insignificant per the XML Recommendation:
Note that the order of attribute specifications in a start-tag or
empty-element tag is not significant.
Therefore, XMLStreamWriter provides no way to constrain attribute ordering.
In general, the XML recommendations will all consider attribute ordering to be insignificant, but see the section on attribute processing in the XML Normalization Recommendation or the Canonical XML Recommendation if your application has a need for attribute ordering.
Related Topics
Noclassdeffounderror While Trying to Run My Jar with Java.Exe -Jar...What's Wrong
Performance Difference Between Java 8 Lambdas and Anonymous Inner Classes
Numeric Textfield for Integers in Javafx 8 with Textformatter And/Or Unaryoperator
Class Object of Generic Class (Java)
Apache Poi Error Loading Xssfworkbook Class
What Are Shadow Variables in Java
Shuffle a List of Integers with Java 8 Streams API
Keystore Type: Which One to Use
How to Hide Cursor in a Swing Application
Java Server with Multiclient Communication
Count Occurrences of Words in Arraylist
What Does Super.Paintcomponent(G) Do
Java Import VS Code Performance
How Pause and Then Resume a Thread
Running a Java Program as an Exe in Windows Without Jre Installed