我有以下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文件来做那个? 我在另一篇文章中看到了这段代码,但无法理解
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));
}
答案 0 :(得分:5)
此代码段应该按您的意愿执行。如果您只想从树中删除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));
//------------------------------------------------------------------------