将文件中的XML替换为“文档”在Java中 [英] Replacing XML in File from "Document" in Java
问题描述
在我的文档数据类型中重新布置它的工作原理很棒:)
这里有什么问题:如何将更改后的document-model存储回我的文件?我必须通过使用标准文件功能(通过蒸汽等)来做到这一点吗?这是一个更优雅的方式吗? ; - )
这是我已经制定的代码,也许这可以帮助。 (方法getParsedXML只是将文件的转换放入额外的方法)
文档tmpDoc = getParsedXML(currentGPX);
// XML Parsind测试:
//访问标签属性< tag attribut =bla>
System.out.println(tmpDoc.getElementsByTagName(wpt)。item(0).getAttributes()。getNamedItem(lat)。getTextContent());
//访问子元素的值< a>< CHILD> ValueOfChild< / CHILD>< / a>
System.out.println(tmpDoc.getElementsByTagName(wpt)。item(0).getChildNodes()。item(5).getTextContent());
//替换对标签属性的访问
tmpDoc.getElementsByTagName(wpt)。item(0).getAttributes()。getNamedItem(lat)。setTextContent(139.921055008) ;
System.out.println(tmpDoc.getElementsByTagName(wpt)。item(0).getAttributes()。getNamedItem(lat)。getTextContent());
//替换对子元素值的访问
tmpDoc.getElementsByTagName(wpt)。item(0).getChildNodes()。item(5).setTextContent(Cala SantVicenç - 马略卡岛2);
System.out.println(tmpDoc.getElementsByTagName(wpt)。item(0).getChildNodes()。item(5).getTextContent());
不幸的是,Java XML API主要用于解析XML ,但是奇怪地缺少将XML存储在文件中的明显API。
您可以使用XSL转换API,如这个例子。
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.
这篇关于将文件中的XML替换为“文档”在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!