Replacing XML in a file from "Document" in Java
after processing my first steps in working with XML in java. I am now at the point where I want to update some data in the XML / GPX file ...
Reusing it in my "Document" works great :)
The question arises: how can I save the modified "document" -model back to my file? Should I be doing this using standard file functions (via pairs, etc.) and another more elegant way to do it ?; -)
Here is the code I have already worked out, maybe it can help. (the getParsedXML method just transfers the conversion from the file to an additional method)
Document tmpDoc = getParsedXML(currentGPX);
//XML Parsind tests:
// Access to tag attribute <tag attribut="bla">
System.out.println(tmpDoc.getElementsByTagName("wpt").item(0).getAttributes().getNamedItem("lat").getTextContent());
// Access to the value of an child element <a><CHILD>ValueOfChild</CHILD></a>
System.out.println(tmpDoc.getElementsByTagName("wpt").item(0).getChildNodes().item(5).getTextContent());
// Replacing access to tag attribute
tmpDoc.getElementsByTagName("wpt").item(0).getAttributes().getNamedItem("lat").setTextContent("139.921055008");
System.out.println(tmpDoc.getElementsByTagName("wpt").item(0).getAttributes().getNamedItem("lat").getTextContent());
// Replacing access to child element value
tmpDoc.getElementsByTagName("wpt").item(0).getChildNodes().item(5).setTextContent("Cala Sant Vicenç - Mallorca 2");
System.out.println(tmpDoc.getElementsByTagName("wpt").item(0).getChildNodes().item(5).getTextContent());
0
a source to share
1 answer
Unfortunately, Java XML APIs are mainly for parsing XML, but strangely there is no obvious API for storing XML in a file.
You can do this using the XSL Transformation API, as in this example .
+2
a source to share