Replacing XML in File from "Document" in Java

Posted by poeschlorn on Stack Overflow See other posts from Stack Overflow or by poeschlorn
Published on 2010-05-07T12:03:48Z Indexed on 2010/05/07 12:08 UTC
Read the original article Hit count: 165

Filed under:
|
|

Hi,

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());

© Stack Overflow or respective owner

Related posts about java

Related posts about Xml