You may want to use XMLModier of vtd-xml to do it in a cool way, which is to append the byte content directly... You just need to call XMLModier's insertAfterElement()...
below is a link to the code sample: Incrementally Modify XML in Java:
import com.ximpleware.*;
import java.io.*;
public class ModifyXML {
public static void main(String[] s) throws Exception{
VTDGen vg = new VTDGen(); // Instantiate VTDGen
XMLModifier xm = new XMLModifier(); //Instantiate XMLModifier
if (vg.parseFile("old.xml",false)){
VTDNav vn = vg.getNav();
xm.bind(vn);
// first update the value of attr
int i = vn.getAttrVal("attr");
if (i!=-1){
xm.updateToken(i,"value");
}
// navigate to <a>
if (vn.toElement(VTDNav.FC,"a")) {
// update the text content of <a>
i=vn.getText();
if (i!=-1){
xm.updateToken(i," new content ");
}
// insert an element before <a> (which is the cursor element)
xm.insertBeforeElement("<b/>\n\t");
// insert an element after <a> (which is the cursor element)
xm.insertAfterElement("\n\t<c/>");
}
xm.output(new FileOutputStream("new.xml"));
}
}
}