How to read XML using XPath in Java -


i want read xml data using xpath in java, information have gathered not able parse xml according requirement.

here want do:

get xml file online via url, use xpath parse it, want create 2 methods in it. 1 in enter specific node attribute id, , child nodes result, , second suppose want specific child node value only

<?xml version="1.0"?> <howto>   <topic name="java">       <url>http://www.rgagnonjavahowto.htm</url>   <car>taxi</car>   </topic>   <topic name="powerbuilder">        <url>http://www.rgagnon/pbhowto.htm</url>        <url>http://www.rgagnon/pbhowtonew.htm</url>   </topic>   <topic name="javascript">         <url>http://www.rgagnon/jshowto.htm</url>   </topic>  <topic name="vbscript">        <url>http://www.rgagnon/vbshowto.htm</url>  </topic>  </howto> 

in above example want read elements if search via @name , 1 function in want url @name 'javascript' return 1 node element.

i hope cleared question :)

thanks.

kai

you need along lines of this:

documentbuilderfactory factory = documentbuilderfactory.newinstance(); documentbuilder builder = factory.newdocumentbuilder(); document doc = builder.parse(<uri_as_string>); xpathfactory xpathfactory = xpathfactory.newinstance(); xpath xpath = xpathfactory.newxpath(); xpathexpression expr = xpath.compile(<xpath_expression>); 

then call expr.evaluate() passing in document defined in code , return type expecting, , cast result object type of result.

if need specific xpath expressions, should ask separate questions (unless question in first place here - understood question how use api in java).

edit: (response comment): xpath expression text of first url element under powerbuilder:

/howto/topic[@name='powerbuilder']/url/text() 

this second:

/howto/topic[@name='powerbuilder']/url[2]/text() 

you code:

expr.evaluate(doc, xpathconstants.string); 

if don't know how many urls in given node, should rather this:

xpathexpression expr = xpath.compile("/howto/topic[@name='powerbuilder']/url"); nodelist nl = (nodelist) expr.evaluate(doc, xpathconstants.nodeset); 

and loop on nodelist.


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -