1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
public class TestDom {
/**
* @param args
*/
public static void main(String[] args) {
// chech parameters
if (args.length != 2) {
System.err.println("Usage: java TestDom file.xml tagToDelete");
System.exit(1);
}
// xml dom in memory
Document dom = null;
// xml file
File file = new File(args[0]);
// element to delete
String tagToDelete = args[1];
// create dom
try {
dom = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(file);
}
catch (Exception e) {
System.err.println(e);
System.exit(1);
}
// update dom (remove elements)
NodeList nodes = dom.getElementsByTagName(tagToDelete);
for (int i = 0 ; i < nodes.getLength() ; i++) {
Node node = nodes.item(i);
node.getParentNode().removeChild(node);
}
// serialize dom
try {
OutputFormat format = new OutputFormat(dom);
XMLSerializer output = new XMLSerializer(new FileOutputStream(file), format);
output.serialize(dom);
}
catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
}
} |
Partager