从 Java 中的 XML 文件中删除节点及其元素 [英] Delete a node and its elements from an XML file in java

查看:68
本文介绍了从 Java 中的 XML 文件中删除节点及其元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下xml:

<table1>
    <row0>
        <column1>String</column1>
        <column2>int</column2>
    </row0>

    <row1>
        <column1>aa</column1>
        <column2>65432</column2>
    </row1>

    <row2>
        <column1>ww</column1>
        <column2>1111</column2>
    </row2>

    <row3>
        <column1>fff</column1>
        <column2>333</column2>
    </row3>

    <row4>
        <column1>jj</column1>
        <column2>2</column2>
    </row4>
</table1>

我想删除节点 row3 及其元素.我正在用 java.how 编写那个 XML 文件?我在另一篇文章中看到了这段代码,但无法理解

and i want to delete the node row3 and its elements. I am writing that XML file in java.how to do that? i saw this code in another post but couldn't understand it

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document document = dbf.newDocumentBuilder().parse(new File("input.xml"));

    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    XPathExpression expression = xpath.compile("//A/B[C/E/text()=13]");

    Node b13Node = (Node) expression.evaluate(document, XPathConstants.NODE);
    b13Node.getParentNode().removeChild(b13Node);

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    t.transform(new DOMSource(document), new StreamResult(System.out));
}

推荐答案

此代码片段应该可以满足您的需求.如果您只想从树中删除 row3 元素,则不必使用(并理解)强大的 XPATH!

This code snippet should do what you want to. If you just want to remove the row3 element from your tree you don't have to use (and understand) the overmighty XPATH!

// -------------- building the document out of the file  -----------------
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document document = dbf.newDocumentBuilder().parse(new File("input.xml"));
//------------------------------------------------------------------------

// -------------- finding the right node and removing it -----------------
Element table = document.getDocumentElement();
Node row3 = table.getElementsByTagName("row3").item(0);
table.removeChild(row3);
//------------------------------------------------------------------------

// -------------- printing the resulting tree to the console -------------
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.transform(new DOMSource(document), new StreamResult(System.out));
//------------------------------------------------------------------------

这篇关于从 Java 中的 XML 文件中删除节点及其元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆