Remove XML Node using java parser

前端 未结 4 1084
迷失自我
迷失自我 2020-12-02 21:41

In the below sample XML, how to remove Entire B Node if E=13 using java parser.


   
     
       
         11         


        
4条回答
  •  没有蜡笔的小新
    2020-12-02 22:15

    It's easy if you are using DOM. Just traverse the document and keep track of the B nodes. When you hit an E=13 node, remove the B node. Here is some code to help:

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Document doc = factory.newDocumentBuilder().parse(new File("file.xml"));
    DocumentTraversal traversal = (DocumentTraversal) doc;
    Node a = doc.getDocumentElement();
    NodeIterator iterator = traversal.createNodeIterator(a, NodeFilter.SHOW_ELEMENT, null, true);
    Element b = null;
    for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
        Element e = (Element) n;
        if ("B".equals(e.getTagName())) {
            b = e;
        } else if ("E".equals(e.getTagName()) && "13".equals(e.getTextContent()) && b != null) {
            a.removeChild(b);
        }
    }
    

提交回复
热议问题