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」で子リストを取得します。要素リストのサイズを取得し、最後の要素の後のインデックスに挿入します。最初の 2 回の挿入は問題ありませんが、3 回目の挿入以降は奇妙な問題に直面します。新しい要素 '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を使用してこれを行う方法はありますか?
どんな助けでも大歓迎です