Hi!
Ich habe folgende XML-Datei("NewFile.xml"):
Die Datei möchte ich nun so sortieren, das die child-Elemente in Reihenfolge ihrer id-Werte stehen.
Mein Programm:
Wenn ich mein Programm starte, erhalte ich folgende Fehlermeldung:
PS: In Zeile 27 erhalte ich eine "Type safety"-Warning. Kann die 'beseitigt' werden? (abgesehen von "@SuppressWarnings("unchecked")")
Ich habe folgende XML-Datei("NewFile.xml"):
Code:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child>
<id>1</id>
<data>
<data1>11</data1>
<data2>12</data2>
<data3>13</data3>
</data>
</child>
<child>
<id>3</id>
<data>
<data1>31</data1>
<data2>32</data2>
<data3>33</data3>
</data>
</child>
<child>
<id>2</id>
<data>
<data1>21</data1>
<data2>22</data2>
<data3>23</data3>
</data>
</child>
</root>
Die Datei möchte ich nun so sortieren, das die child-Elemente in Reihenfolge ihrer id-Werte stehen.
Mein Programm:
Code:
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class XMLMain {
/**
* @author Ingo
* @param no args
*/
public static void main(String[] args) {
Document doc = null;
try {
SAXBuilder builder = new SAXBuilder();
doc = builder.build(new File("NewFile.xml"));
// printDocument(doc);
Element root = doc.getRootElement();
List<Element> children = root.getChildren("child");
Collections.sort(children, new MyComparator());
root.setContent(children);
printDocument(doc);
} catch (IOException e) {
// z. B. Dateifehler
e.printStackTrace();
} catch (JDOMException e) {
// z. B. ungültiges XML-Dokument
e.printStackTrace();
}
}
public static void printDocument(Document doc) throws IOException {
Format format = Format.getPrettyFormat();
XMLOutputter fmt = new XMLOutputter(format);
fmt.output(doc, System.out);
}
}
//this class is used for the sorting of the elements
class MyComparator implements Comparator<Element> {
public int compare(Element o1, Element o2) {
int id1 = Integer.parseInt(o1.getChild("id").getText());
int id2 = Integer.parseInt(o2.getChild("id").getText());
return id1 - id2;
}
}
Wenn ich mein Programm starte, erhalte ich folgende Fehlermeldung:
Exception in thread "main" org.jdom.IllegalAddException: The Content already has an existing parent "root"
at org.jdom.ContentList.add(ContentList.java:218)
at org.jdom.ContentList.add(ContentList.java:140)
at org.jdom.ContentList.set(ContentList.java:497)
at org.jdom.ContentList$FilterListIterator.set(ContentList.java:961)
at java.util.Collections.sort(Unknown Source)
at xml.XMLMain.main(XMLMain.java:29)
PS: In Zeile 27 erhalte ich eine "Type safety"-Warning. Kann die 'beseitigt' werden? (abgesehen von "@SuppressWarnings("unchecked")")