java - iterating items with namespace prefix in XML using DOM4J -


the problem namespace prefix. below sample xml code.

<rss version="2.0">     <channel>                 <item>             <ed:filing xmlns:ed="http://www.ed.com">                 <ed:name>abc</ed:name>                 <ed:files>                     <ed:file ed:id="1" ed:file="abc.htm" />                     <ed:file ed:id="2" ed:file="abc.zip" />                 </ed:files>             </ed:filing>         </item>         <item>             <ed:filing xmlns:ed="http://www.ed.com">                 <ed:name>cdf</ed:name>                 <ed:files>                     <ed:file ed:id="1" ed:file="cdf.htm" />                     <ed:file ed:id="2" ed:file="cdf.zip" />                 </ed:files>             </ed:filing>         </item>        </channel> </rss> 

i parse xml code java , dom4j , print out like;

name    file1    file2 abc     abc.htm  abc.zip cdf     cdf.htm  cfd.zip 

here's java code;

saxreader reader = new saxreader(); document document = reader.read( inputfile );            list<node> nodes = document.selectnodes("//rss/channel/item");  (node node : nodes) {     ??? how can access "ed:name" , "ed:file" ??? } 

there several options, here 1 using xpath , namespace mappings:

    map<string, string> nc = new hashmap<string, string>() {         {             put("ed", "http://www.ed.com");         }     };      system.out.printf("name\tfile 1\tfile 2\n");     (node node : nodes) {         xpath xp = document.createxpath(".//ed:name");         xp.setnamespaceuris(nc);         string name = xp.selectsinglenode(node).gettext();          xp = document.createxpath(".//ed:file[@ed:id='1']/@ed:file");         xp.setnamespaceuris(nc);         string f1 = xp.selectsinglenode(node).gettext();          xp = document.createxpath(".//ed:file[@ed:id='2']/@ed:file");         xp.setnamespaceuris(nc);         string f2 = xp.selectsinglenode(node).gettext();          system.out.printf("%s\t%s\t%s\n", name, f1, f2);     } 

a bit annoying cannot reuse xpath instance in javax.xml.xpath.


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -