Use JDOM to change the element text
import java.io.File;
import java.io.FileWriter;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
public class MainClass {
public static void main(String[] args) throws Exception {
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new File("r.xml"));
Element prologue, title, speech;
prologue = new Element("P");
List actList = document.getRootElement().getChildren("ACT");
document.getRootElement().removeChildren("ACT");
document.getRootElement().addContent(prologue);
for (int act = 0; act < actList.size(); act++) {
document.getRootElement().addContent((Element) actList.get(act));
}
title = new Element("TITLE");
title.setText("test");
prologue.addContent(title);
speech = new Element("SPEECH");
speech.setText("test");
prologue.addContent(speech);
XMLOutputter xmlOutputter = new XMLOutputter();
xmlOutputter.output(document, new FileWriter("rewrite.xml"));
}
}
Related examples in the same category