So ändern Sie eine XML-Datei in Java - (JDOM Parser)
JDOM XML parserBeispiel zum Ändern einer vorhandenen XML-Datei:
-
Fügen Sie ein neues Element hinzu
-
Vorhandenes Elementattribut aktualisieren
-
Vorhandenen Elementwert aktualisieren
-
Vorhandenes Element löschen
1. XML-Datei
Siehe vor und nach der XML-Datei.
File : file.xml - Ursprüngliche XML-Datei.
yong mook kim example 5000
Aktualisieren Sie die obige XML-Datei später über den JDOM XML Parser.
-
Fügen Sie unter "Personal" ein neues "Alter" -Element hinzu
-
Aktualisieren Sie das Personalattribut id = 2
-
Aktualisieren Sie den Gehaltswert auf 7000
-
Löschen Sie das Element "firstname" unter staff
File : file.xml - Neu geänderte XML-Datei.
mook kim example 7000 28
2. JDOM-Beispiel
JDOM-Parser zum Aktualisieren oder Ändern einer vorhandenen XML-Datei.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
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 ModifyXMLFile {
public static void main(String[] args) {
try {
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("c:\\file.xml");
Document doc = (Document) builder.build(xmlFile);
Element rootNode = doc.getRootElement();
// update staff id attribute
Element staff = rootNode.getChild("staff");
staff.getAttribute("id").setValue("2");
// add new age element
Element age = new Element("age").setText("28");
staff.addContent(age);
// update salary value
staff.getChild("salary").setText("7000");
// remove firstname element
staff.removeChild("firstname");
XMLOutputter xmlOutput = new XMLOutputter();
// display nice nice
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc, new FileWriter("c:\\file.xml"));
// xmlOutput.output(doc, System.out);
System.out.println("File updated!");
} catch (IOException io) {
io.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
}
}
}