How to get the full path of a node in XML file in java? -
i have xml file parsed xpath parameters in it, , want full path each parameter code didn't work reason. the code:
arraylist<string> names = new arraylist<string>(); arraylist<string> paths = new arraylist<string>(); url oracle = new url("http://weather.yahooapis.com/forecastrss?w=2502265"); inputstream = oracle.openstream(); org.w3c.dom.document doc = null; documentbuilderfactory domfactory; documentbuilder builder; try { domfactory = documentbuilderfactory.newinstance(); domfactory.setnamespaceaware(true); builder = domfactory.newdocumentbuilder(); doc = builder.parse(is); } catch (exception ex) { system.err.println("unable load xml: " + ex); } xpathfactory factory = xpathfactory.newinstance(); xpath xpath = factory.newxpath(); xpathexpression expr = xpath.compile("//*/@*"); object result = expr.evaluate(doc, xpathconstants.nodeset); nodelist nl = (nodelist) result; for(int j=0 ; j < nl.getlength() ; j++){ names.add(nl.item(j).getnodename()); node node = nl.item(j); arraylist<string> parents = new arraylist<string>(); while(node.getparentnode() != null){ // didn't gone through loop parents.add(node.getnodename()); node = node.getparentnode(); } system.out.println(parents); }
the expression //*/@*
returns empty nodeset.
the code below retrieve paths need:
import org.w3c.dom.attr; import org.w3c.dom.node; import org.w3c.dom.nodelist; public class { @suppresswarnings("nls") public static void main( string[] args ) throws exception { list< string > names = new arraylist<>(); url oracle = new url( "http://weather.yahooapis.com/forecastrss?w=2502265" ); inputstream = oracle.openstream(); org.w3c.dom.document doc = null; documentbuilderfactory domfactory; documentbuilder builder; try { domfactory = documentbuilderfactory.newinstance(); domfactory.setnamespaceaware(true); builder = domfactory.newdocumentbuilder(); doc = builder.parse(is); } catch (exception ex) { system.err.println("unable load xml: " + ex); } xpathfactory factory = xpathfactory.newinstance(); xpath xpath = factory.newxpath(); xpathexpression expr = xpath.compile( "//*:*/@*" ); object result = expr.evaluate( doc, xpathconstants.nodeset ); nodelist nl = (nodelist) result; for(int j=0 ; j < nl.getlength() ; j++){ names.add( nl.item(j).getnodename()); node node = nl.item(j); string path = "." + node.getnodename() + " = " + node.getnodevalue(); node = ((attr)node).getownerelement(); while( node != null) { path = node.getnodename() + '/' + path; node = node.getparentnode(); } system.out.println( path ); } } }
Comments
Post a Comment