java - Getting attributes values from a node in XML file -
i have xml file , want values of nodes attributes in it, works efficiently when node usual case of nodes named something:something didn't give me result, null. xml file :
<?xml version="1.0" encoding="utf-8" standalone="yes" ?> <rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"> <channel> <title>yahoo! weather - sunnyvale, ca</title> <link>http://us.rd.yahoo.com/dailynews/rss/weather/sunnyvale__ca/*http://weather.yahoo.com/forecast/usca1116_f.html</link> <description>yahoo! weather sunnyvale, ca</description> <language>en-us</language> <lastbuilddate>fri, 18 dec 2009 9:38 pst</lastbuilddate> <ttl>60</ttl> <yweather:location city="sunnyvale" region="ca" country="united states"/> <yweather:units temperature="f" distance="mi" pressure="in" speed="mph"/> </channel> </rss>
the java code :
xpathfactory factory = xpathfactory.newinstance(); xpath xpath = factory.newxpath(); xpathexpression expr = xpath.compile("//rss/@version"); object result = expr.evaluate(doc, xpathconstants.string); system.out.println(result);
the previous java code works efficiently when replacing //rss/@version
//rss/channel/yweather:location/@city
returns me null.
first of all, part before : called namespace. quite important concept in xml. retrieve value namespace have make context aware of namespace. can using
xpath.setnamespacecontext(context);
context
must implementation of namespacecontext. in case, namspaces defined within xml might have namespace resolver can namespaces document directly. class doing this:
public class universalnamespaceresolver implements namespacecontext { private document sourcedocument; public universalnamespaceresolver(document document) { sourcedocument = document; } public string getnamespaceuri(string prefix) { if (prefix.equals(xmlconstants.default_ns_prefix)) { return sourcedocument.lookupnamespaceuri(null); } else { return sourcedocument.lookupnamespaceuri(prefix); } } public string getprefix(string namespaceuri) { return sourcedocument.lookupprefix(namespaceuri); } public iterator getprefixes(string namespaceuri) { return null; } }
read more @ http://www.ibm.com/developerworks/library/x-nmspccontext/
Comments
Post a Comment