开发者

How do I get the exact position to place the clone in an XML (JDom)?

I have the following XML Structure:

<S i="0" id="S1">
     <W C="JJ" id="W1" o1="0" o2="8">Dominant</W>
     <W C="NN" id="W2" o1="9" o2="21">contribution</W>
     <W C="IN" id="W3" o1="22" o2="24">of</W开发者_如何学Python>
     <Term allvalues="PA123:GNX" type="GNX" values="PA123">
       <W C="NN" id="W4" o1="25" o2="29">P450</W>
     </Term>
     <W C="NN" id="W5" o1="30" o2="33">3A4</W>
     <W C="TO" id="W6" o1="34" o2="36">to</W>
     <W C="DT" id="W7" o1="37" o2="40">the</W>
     <W C="JJ" id="W8" o1="41" o2="48">hepatic</W>
     <W C="NN" id="W9" o1="49" o2="61">carcinogenic</W>
     <W C="NN" id="W10" o1="62" o2="72">activation</W>
     <W C="IN" id="W11" o1="73" o2="75">of</W>
     <Term allvalues="PA452609:DRUG" type="DRUG" values="PA452609">
       <W C="NN" id="W12" o1="76" o2="85">aflatoxin</W>
       <W C="NN" id="W13" o1="86" o2="88">B1</W>
     </Term>
     <W C="." id="W14" o1="88" o2="89">.</W>
  </S>

My task is to delete the Term tags but keeping the W tags. I cloned the Ws but when adding them to S I don't know how to guess the correct position.

private void deleteInsideTerms(Element element){
    List allChildren = element.getChildren();
    for(int i = 0; i<allChildren.size(); i++){
        Element child = (Element) allChildren.get(i);
        if(child.getName().equalsIgnoreCase("term")){
                        List<Element> listW = child.getChildren("W");
                        for(int in = 0; in<listW.size(); in++){
                              Element clone = (Element) listW.get(in).clone();
                              child.getParentElement().addContent(**???**, clone);
                        }
                    else
            deleteInsideTerms(child);
    }

}

Does anyone know what I have to insert as index? Thanks.


You shouldn't have to guess the position ;-). In cases like this, it is often easier to remove all the content and then put it back while skipping the items that should be removed (also avoids cloning).

    Element s = doc.getRootElement();
    List<Content> cl = s.removeContent();
    for (Content c : cl) {
        if (c instanceof Element && ((Element) c).getName().equals("Term")) {
            List<Content> sublist = ((Element) c).removeContent();
            for (Content w : sublist) {
                if (w instanceof Element
                        && ((Element) w).getName().equals("W")) {
                    s.addContent(w);
                }
            }
        } else {
            s.addContent(c);
        }
    }

OTOH, if this is just an example of a more general task, maybe you should consider using XSL instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜