简体   繁体   中英

Replacing XML in 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 my XML/GPX file...

Reaplacing it in my "Document" data type works great :)

How here comes the question: how can I store the changed "document"-model back to my file? Do I have to do this by using the standart file-functions (via steams and so on) oder is the a more elegant way to do this? ;-)

Here's the code I already worked out, maybe that could help. (the method getParsedXML is just puting the conversion from the file into an extra 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());

Unofrtunately the Java XML APIs are mainly made for parsing XML, but are strangely missing an obvious API to store XML in a file.

You can do it by using the XSL transformation API as in this example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM