简体   繁体   中英

Remove parent node and keep its children

i have this XML in want to remove link tag and keep all its children

input xml :

  <P>
  <LINK TYPE="ERRATUM" DOI="">
    Der Kommentar zum Artikel Schaefer et al. in Heft 4/91 (S. 238) wurde
    nicht von PD Dr.
    <EM EMTYPE="ITALIC">M. Stöckle</EM>
    (Urologische Klinik, Mainz), sondern von PD Dr.
    <EM EMTYPE="ITALIC">O. Schofer</EM>
    (Kinderklinik der Universität, Mainz) verfasst.
  </LINK>
  </P>

output xml :

  <P>

    Der Kommentar zum Artikel Schaefer et al. in Heft 4/91 (S. 238) wurde
    nicht von PD Dr.
    <EM EMTYPE="ITALIC">M. Stöckle</EM>
    (Urologische Klinik, Mainz), sondern von PD Dr.
    <EM EMTYPE="ITALIC">O. Schofer</EM>
    (Kinderklinik der Universität, Mainz) verfasst.

  </P>

i tried this code but no success!

private void visitRecursively(Node node, Document document, String tagToRemove) {

    // get all child nodes
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {

        // get child node

        Node childNode = list.item(i);

        if(childNode != null){
            if(childNode.getNodeType() == Node.ELEMENT_NODE){
                if(childNode.getNodeName().equals(tagToRemove)){

                    NodeList nodeList = childNode.getChildNodes();
                    Node parentNode = childNode.getParentNode();
                    System.out.println("parent= "+parentNode.getNodeName());
                    for(int j = 0 ; j < nodeList.getLength() ;  ++j ){
                            parentNode.appendChild(nodeList.item(j));
                    }
                }
            }
        }
        visitRecursively(childNode, document, tagToRemove);
    }
}

thanks!

For line-based formatting I'd just parse the text as a List and remove the line(s) including " <LINK " or " </LINK ". Then trim the List to size, removing any blank rows.

Probably quicker than messing around with recursive manipulation of the NodeList.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM