删除代码中XML文件中的内容

时间:2013-04-04 12:54:48

标签: java android xml

我正在开发一个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>

你知道怎么做吗?

3 个答案:

答案 0 :(得分: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.
    }

}

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

答案 1 :(得分:0)

看看this question。这是一个非常受欢迎的问题,对于下次谷歌问题,然后问这里。

答案 2 :(得分:0)

以下是使用VTD-XML删除元素的代码。请注意,它比DOM更简洁,更有效率

//in snake_high_scores.php
//this is a really bad way to learn ajax requests. You should use a framework
$new_highscore= $_POST['score']; 
//store this score in a db maybe you can pickup the user id from a session cookie

 echo json_encode({data => {high_score => $some_highscore}});