user2184060 user2184060 - 7 months ago 23
Java Question

Delete content in XML file in the code

I'm developing an android application, and I would like to delete a small content in my XML file in my application's code.
I would like to delete the content below:

<pma:structure_schemas>
<pma:database name="test" collation="latin1_swedish_ci" charset="latin1">
<pma:table name="agenda">
CREATE TABLE `agenda` (
`id` int(2) NOT NULL AUTO_INCREMENT,
`title` varchar(60) NOT NULL,
`description` varchar(1000) NOT NULL,
`town` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
</pma:table>
</pma:database>
</pma:structure_schemas>


Do you have any idea about how to do ?

Answer

You can use the following code:

import java.io.File;
import javax.xml.*;
import org.w3c.dom.*;

public class DeleteXmlNode {

    public static void deleteNode(String nodedetailsExpression) {//Use your expression here depending upon the node you wnt to delete

        try{
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xpath = xPathFactory.newXPath();
        XPathExpression expression = xpath.compile(nodedetailsExpression);
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        Document document = documentBuilderFactory.newDocumentBuilder().parse(new File("test.xml"));
        Node node = (Node) expression.evaluate(document, XPathConstants.NODE);
        node.getParentNode().removeChild(node);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(new DOMSource(document), new StreamResult(System.out));
        }catch(Exception e){
        //Do your Exception handling over here.
    }

}

Here you need to pass the expression string of the node to be deleted.

Comments