java - Parsing XML file using Xpath in jdk1.4 -
i found following easy solution extracting values xml file.
import java.io.ioexception; import org.w3c.dom.*; import org.xml.sax.saxexception; import javax.xml.parsers.*; import javax.xml.xpath.*; public class xpathexample { public static void main(string[] args) throws parserconfigurationexception, saxexception, ioexception, xpathexpressionexception { documentbuilderfactory domfactory = documentbuilderfactory.newinstance(); domfactory.setnamespaceaware(true); // never forget this! documentbuilder builder = domfactory.newdocumentbuilder(); document doc = builder.parse("c:/temp/books.xml"); xpathfactory factory = xpathfactory.newinstance(); xpath xpath = factory.newxpath(); xpathexpression expr = xpath.compile("//book[author='neal stephenson']/title/text()"); object result = expr.evaluate(doc, xpathconstants.nodeset); nodelist nodes = (nodelist) result; (int = 0; < nodes.getlength(); i++) { system.out.println(nodes.item(i).getnodevalue()); } } }
this uses xpath extract books title author neal stephenson following xml
<inventory> <book year="2000"> <title>snow crash</title> <author>neal stephenson</author> <publisher>spectra</publisher> <isbn>0553380958</isbn> <price>14.95</price> </book> <book year="2005"> <title>burning tower</title> <author>larry niven</author> <author>jerry pournelle</author> <publisher>pocket</publisher> <isbn>0743416910</isbn> <price>5.99</price> </book> <book year="1995"> <title>zodiac</title> <author>neal stephenson</author> <publisher>spectra</publisher> <isbn>0553573862</isbn> <price>7.50</price> </book> <!-- more books... --> </inventory>
now works fine on jdk5 using jdk 1.4 can converted java 1.4 equivalent?
all trying extract value xml element. example, in above xml, want equivalent of getelementbytag("title").
thanks
quick google resulted in links this , this confirm jaxp can downloaded separately , run on top of jdk 1.4.2. might run configuration problems mentioned in apache link. luck!
Comments
Post a Comment