How can I modify an xml file, delete and write a child, in java?


I have an eclipse project based on JAVA, in this project I have an XML file where I keep data from nursing staff, what I want is to eliminate a nurse (a child) from this file, I also want to write about this data . please give me examples, some solution. Thank you.

asked by user9054 12.06.2016 в 01:56

1 answer


Java has several components that can be useful for locating an item and altering an XML document. Since you do not mention more details of which of them you are using I offer you an example with the method that I know best:

// 1. cargar el XML original
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("ruta/al/archivo.xml");

// 2. buscar y eliminar el elemento <enfermera id="3"> de entre 
//    muchos elementos <enfermera> ubicados en cualquier posicion del documento
NodeList items = doc.getElementsByTagName("enfermera");
for (int ix = 0; ix < items.getLength(); ix++) {
    Element element = (Element) items.item(ix);
    // elejir un elemento especifico por algun atributo
    if (element.getAttribute("id").equalsIgnoreCase("3")) {
        // borrar elemento

// 3. Exportar nuevamente el XML
Transformer transformer = TransformerFactory.newInstance().newTransformer();
Result output = new StreamResult(new File("ruta/a/resultado.xml"));
Source input = new DOMSource(doc);
transformer.transform(input, output);

I hope it helps you.

answered by 12.06.2016 в 02:38