gpt4 book ai didi

java - 从java中的XML文件中删除节点及其元素

转载 作者:数据小太阳 更新时间:2023-10-29 02:56:22 25 4
gpt4 key购买 nike

我有以下 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 编写该 XML 文件。该怎么做?我在另一篇文章中看到这段代码,但无法理解

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!

// -------------- 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 - 从java中的XML文件中删除节点及其元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33759441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com