3

我正在开发一个 android 应用程序,我想在我的应用程序代码中删除我的 XML 文件中的一个小内容。我想删除以下内容:

<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>

你有什么想法吗?

4

3 回答 3

2

您可以使用以下代码:

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.
    }

}

这里需要传递要删除的节点的表达式字符串。

于 2013-04-04T13:08:37.563 回答
0

看看这个问题。这是一个很热门的问题,下次google问题再问这里。

于 2013-04-04T12:58:55.657 回答
0

这是使用VTD-XML删除元素的代码。请注意,它比 DOM 更加简洁和高效

import com.ximpleware.*;
import java.io.*;

public class removeElement {
    public static void main(String s[]) throws VTDException,IOException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", false))
            return;
        VTDNav vn = vg.getNav();
        XMLModifier xm = new XMLModifier(vn);
        AutoPilot ap = new AutoPilot(vn);
        ap.selectXPath("/ClOrdIDS/ClOrdID[@id='3']");
        int i=0;
        while((i=ap.evalXPath())!=-1){
            xm.remove();
        }
        xm.output("output.xml");
    }
}
于 2016-04-18T21:49:06.923 回答