在处理完在 java 中使用 XML 的第一步之后,我现在想要更新 XML/GPX 文件中的一些数据...
将其替换为我的“文档”数据类型效果很好:)
问题来了:如何将更改后的“文档”模型存储回我的文件?我是否必须使用标准文件功能(通过 Steam 等)来执行此操作,或者是更优雅的方法来执行此操作? ;-)
这是我已经编写好的代码,也许会有所帮助。 (方法 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());
最佳答案
不幸的是,Java XML API 主要用于解析 XML,但奇怪的是缺少一个明显的 API 将 XML 存储在文件中。
您可以使用 XSL 转换 API 来完成此操作,如 this example 中所示。 .
关于java - 在Java中从 "Document"替换文件中的XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2788345/