简体   繁体   English

从Java中的“文档”替换文件中的XML

[英]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... 处理完在Java中使用XML的第一步之后,现在我要更新XML / GPX文件中的某些数据...

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? 我是否必须通过使用标准文件功能(通过Steam等)来执行此操作,还是更优雅的方法? ;-) ;-)

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) (方法getParsedXML只是将文件的转换转换为额外的方法)

                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. 不幸的是,Java XML API主要用于解析XML,但奇怪的是缺少明显的API将XML存储在文件中。

You can do it by using the XSL transformation API as in this example . 您可以通过本示例中的XSL转换API来实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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