Hi all,
I have a task like the following:
My original XML-file is like this:
And I have to add a new Tag between <Stichwort> and <Sachgebiet> called <Fachgebiet>, and a comment at the end, so it's going to be like this:
I already started the DOM program, something like this:
But it didn't work. I'm stuck. I think I completely messed it up. Can somebody help me?
Thanks a lot!
Andre
I have a task like the following:
My original XML-file is like this:
Code:
<Karteikasten>
<Karteikarte>
<Stichwort>XML</Stichwort>
<Sachgebiet>Webtechnologie</Sachgebiet>
. . .
</Karteikarte>
<Karteikarte>
. . .
</Karteikarte>
</Karteikasten>
And I have to add a new Tag between <Stichwort> and <Sachgebiet> called <Fachgebiet>, and a comment at the end, so it's going to be like this:
Code:
<Karteikasten>
<Karteikarte>
<Stichwort>XML</Stichwort>
[b]<Fachgebiet>EDV</Fachgebiet>[/b]
<Sachgebiet>Webtechnologie</Sachgebiet>
. . .
</Karteikarte>
<Karteikarte>
. . .
</Karteikarte>
[b]<!-- Comment here -->[/b]
</Karteikasten>
I already started the DOM program, something like this:
Code:
// Modifizieren der XML-Struktur
// Ändern und Einfügen eines Elementes
import org.w3c.dom.*;
import org.apache.xerces.parsers.DOMParser;
import java.io.*;
import org.apache.xerces.dom.*; // neu
// importe für DateFormater:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Aufgabe3 {
DOMParser myParser;
File xmlFile;
Document xmlDoc;
Element docRoot;
public Aufgabe3() {}
public static void main(String args[]) {
try {
DOMParser myParser = new DOMParser();
// Parsen des Dokumentes
File myFile = new File("Karteikasten.xml");
myParser.parse("file:///" + myFile.getAbsolutePath());
Document myDoc = myParser.getDocument();
Element kk = myDoc.getDocumentElement();
Element fachgebiet = myDoc.createElement("Fachgebiet");
kk.appendChild(fachgebiet);
fachgebiet.appendChild(myDoc.createTextNode("EDV"));
Node element = myDoc.getElementsByTagName("Sachgebiet").item(0);
element = element.getNextSibling();
Node parent = element.getParentNode();
parent.insertBefore(element);
myDoc.createComment("Comment here");
} catch (java.io.IOException ioe) {
System.out.println(ioe.getMessage());
} catch (org.xml.sax.SAXException saxex) {
System.out.println(saxex.getMessage());
}
}
}
But it didn't work. I'm stuck. I think I completely messed it up. Can somebody help me?
Thanks a lot!
Andre