开发者

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).getChild开发者_JAVA技巧Nodes().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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜