can't delete conditionally from xml using Java -
i've xml file need delete elements depending on attribute value. unconditional deletion works fine won't:
nodelist nodes = doc.getelementsbytagname("host"); element d; ( int = 0; < nodes.getlength(); i++ ) { string state = nodes.item(i).getchildnodes().item(0).getattributes().item(0).gettextcontent(); if("down".equals(state)){ d= (element) nodes.item(0); d.getparentnode().removechild(d); system.out.println(state); } }
there couple of problems code. first line
string state = nodes.item(i).getchildnodes().item(0).getattributes().item(0).gettextcontent();
which assumes 1) there no text nodes between child elements, , 2) attribute looked first attribute in list. makes code brittle , subject failure if format of input document change.
the second problem while iterating on node list, of members of list removed parent. behavior of list if detaching/removing children parent not specified in dom api, why effect vary between implementations. not sure if case here, wouldn't depend on guessing.
i suggest using xpath instead (much clearer , shorter). this:
xpath xp = xpathfactory.newinstance().newxpath(); nodelist list = (nodelist) xp.evaluate("//node[*[@* = 'down']]", doc, xpathconstants.nodeset); for(int i=0; < list.getlength(); ++i) { node node = list.item(i); node.getparentnode().removechild(node); }
the expression //node[*[@* = 'down']]
selects <node>
elements have child element has attribute value down
.
Comments
Post a Comment