我正在使用 JDOM 创建和修改 KML 文件。每隔 5 秒,我就会从客户端应用程序收到新的纬度、经度和时间值。我需要修改现有文件并向其中添加最新的纬度、经度和时间值。
XML文件如下所示
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2"
xmlns:gx="http://www.google.com/kml/ext/2.2">
<Document>
<Folder>
<Placemark>
<name>deviceA</name>
<gx:Track>
<when>2015-06-28T17:02:09Z</when>
<when>2015-06-28T17:02:35Z</when>
<gx:coord>3.404258 50.605892 100.000000</gx:coord>
<gx:coord>3.416446 50.604040 100.000000</gx:coord>
</gx:Track>
</Placemark>
<Placemark>
<name>deviceB</name>
<gx:Track>
<when>2015-06-28T17:02:09Z</when>
<when>2015-06-28T17:02:35Z</when>
<gx:coord>3.403133 50.601702 100.000000</gx:coord>
<gx:coord>3.410171 50.597344 100.000000</gx:coord>
</gx:Track>
</Placemark>
</Folder>
</Document>
</kml>
我使用以下代码插入值
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File(outputFile);
try {
Document doc = (Document) builder.build(xmlFile);
Element rootNode = doc.getRootElement();
Element docNode = rootNode.getChild("Document",ns);
Element folNode = docNode.getChild("Folder",ns);
List list = folNode.getChildren("Placemark",ns);
if(list.size()>0)
{
Element node = (Element) list.get(deviceid);
Element tracknode = node.getChild("Track",ns2);
List wlist = tracknode.getChildren("when",ns);
Element newWhen = new Element("when",ns);
newWhen.setText(whentext);
Element newCoord = new Element("coord",ns2);
newCoord.setText(coordtext);
System.out.println("When size:"+wlist.size());
int index =0;
if(wlist.size()==0) index =0;
else index= wlist.size()+1;
tracknode.addContent(index, newWhen);
tracknode.addContent(newCoord);
}
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
FileOutputStream writer = new FileOutputStream(outputFile);
outputter.output(doc, writer);
writer.flush();
writer.close();
} catch (IOException io) {
System.out.println(io.getMessage());
} catch (JDOMException jdomex) {
System.out.println(jdomex.getMessage());
}
'gx:coord' 部分正确插入到元素的末尾,但新的 when 元素需要插入到元素 'when' 的末尾。所以我得到带有标签'when'的孩子列表。获取元素列表的大小并插入到最后一个元素之后的索引处。前两次插入没问题,第三次插入以后我遇到了一个奇怪的问题。新元素“when”被插入到现有的 when 元素之间,而不是插入到 when 元素列表的末尾。例如
<gx:Track>
<when>2015-06-28T17:02:09Z</when>
<when>2015-06-28T17:02:44Z</when>
<when>2015-06-28T17:02:35Z</when>
<gx:coord>3.404258 50.605892 100.000000</gx:coord>
<gx:coord>3.416446 50.604040 100.000000</gx:coord>
<gx:coord>3.429492 50.602078 100.000000</gx:coord>
</gx:Track>
我想在所有现有的 when 元素之后插入新的 'when' 元素。无论如何在java中使用JDOM来做到这一点?
任何帮助表示赞赏