Deleting XML nodes using a Java parser

In the following example XML, if a Java parser is used, if e = 13, how to delete the entire B node

<xml>
   <A>
     <B>
       <C>
         <E>11</E>
         <F>12</F>
       </C>
    </B>
    <B>
       <C>
         <E>13</E>
         <F>14</F>
      </C>
    </B>
  </A>

Please give me some advice

Solution

Alternative DOM methods

Alternatively, you can use the XPath function in the JDK to find the "B" element with the value of "13" and delete it from its parent instead of powerfully traversing the XML document:

import java.io.File;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;
import org.w3c.dom.*;

public class Demo {

    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));
    }

}

The advantage of using XPath is that it is easier to maintain if the structure change is just a line of code change In addition, if the depth of your document grows, XPath - based solutions maintain the same number of lines

Non DOM method

If you don't want to implement XML as dom You can use transformer and stylesheet to delete nodes:

> http://download.oracle.com/javase/6/docs/api/javax/xml/transform/Transformer.html

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>