parse xml using dom java -
parse xml using dom java -
i have bellow xml:
<modelingoutput> <listoftopics> <topic id="1"> <token id="354">wish</token> </topic> </listoftopics> <rankeddocs> <topic id="1"> <documents> <document id="1" numwords="0"/> <document id="2" numwords="1"/> <document id="3" numwords="2"/> </documents> </topic> </rankeddocs> <listofdocs> <documents> <document id="1"> <topic id="1" percentage="4.790644689978203%"/> <topic id="2" percentage="11.427632949428334%"/> <topic id="3" percentage="17.86913349249596%"/> </document> </documents> </listofdocs> </modelingoutput>
Ι want parse xml file , topic id , percentage listofdocs
the first way document element xml , check if grandfather node listofdocs. element document exist in rankeddocs , in listofdocs, have big list.
so wonder if exist improve solution parse xml avoiding if statement?
my code:
public void parse(){ document dom = null; documentbuilderfactory dbf = documentbuilderfactory.newinstance(); documentbuilder db = dbf.newdocumentbuilder(); inputsource = new inputsource(new stringreader(xml)); dom = db.parse(is); element doc = dom.getdocumentelement(); nodelist documentnl = doc.getelementsbytagname("document"); (int = 1; <= documentnl.getlength(); i++) { node item = documentnl.item(i); node parentnode = item.getparentnode(); node grandpnode = parentnode.getparentnode(); if(grandpnode.getnodename() == "listofdocs"{ //get value } } }
first, when checking node name shouldn't compare string
s using ==
. utilize equals
method instead.
you can utilize xpath evaluate document topic
elements under listofdocs
:
xpathfactory xpathfactory = xpathfactory.newinstance(); xpath xpath = xpathfactory.newxpath(); xpathexpression xpathexpression = xpath.compile("//listofdocs//document/topic"); nodelist topicnl = (nodelist) xpathexpression.evaluate(dom, xpathconstants.nodeset); for(int = 0; < topicnl.getlength(); i++) { ...
java xml dom
Comments
Post a Comment