Mahesh Singh Mahesh Singh - 2 months ago 7
HTML Question

find max number of tag inside a tag in xml file

i have xml page and i want to find which tag contain most number of tag how do i get that i am pasting a data of xml file below

<node id="46547591" lat="30.852474" lon="75.8634368" version="1">
<tag k="created_by" v="JOSM" />
</node>
<node id="46547602" lat="30.8525738" lon="75.8634929" version="1">
<tag k="created_by" v="JOSM" />
</node>
<node id="46547607" lat="30.8525862" lon="75.8640606" version="1">
<tag k="created_by" v="JOSM" />
</node>
<node id="46547616" lat="30.8532422" lon="75.8640407" version="1">
<tag k="name" v="Tathgar Jathere" />
<tag k="amenity" v="place_of_worship" />
<tag k="religion" v="sikh" />
<tag k="denomination" v="Devotees of Baba Namdev" />
</node>


As you can see above data the maximum number of tag is last node tag and i wanna count the number of tag.
please help me as soon as possible

Answer

Select the <node> elements and for each element compare the number of <tag> elements in it.

Example Code

String htmlString = "<node id=\"46547591\" lat=\"30.852474\" lon=\"75.8634368\" version=\"1\"> \r\n" + 
        "<tag k=\"created_by\" v=\"JOSM\" /> \r\n" + 
        "</node>\r\n" + 
        "<node id=\"46547602\" lat=\"30.8525738\" lon=\"75.8634929\" version=\"1\"> \r\n" + 
        "<tag k=\"created_by\" v=\"JOSM\" /> \r\n" + 
        "</node>\r\n" + 
        "<node id=\"46547607\" lat=\"30.8525862\" lon=\"75.8640606\" version=\"1\"> \r\n" + 
        "<tag k=\"created_by\" v=\"JOSM\" /> \r\n" + 
        "</node>\r\n" + 
        "<node id=\"46547616\" lat=\"30.8532422\" lon=\"75.8640407\" version=\"1\"> \r\n" + 
        "<tag k=\"name\" v=\"Tathgar Jathere\" /> \r\n" + 
        "<tag k=\"amenity\" v=\"place_of_worship\" /> \r\n" + 
        "<tag k=\"religion\" v=\"sikh\" /> \r\n" + 
        "<tag k=\"denomination\" v=\"Devotees of Baba Namdev\" /> \r\n" + 
        "</node>";
Document doc = Jsoup.parse(htmlString);

Element maxTags=null;

for (Element node : doc.select("node")) {
    Elements tagElements = node.select("tag");
    if(tagElements.size()>0){
        maxTags = maxTags==null || maxTags.select("tag").size()<tagElements.size() ? node : maxTags;
    }
}

System.out.println("Maximum number of tags in a node: " + maxTags.select("tag").size());
System.out.println("Node with maximum number of tags:\n\t" + maxTags.toString().replace("\n", "\n\t"));

Output

Maximum number of tags in a node: 4
Node with maximum number of tags:
    <node id="46547616" lat="30.8532422" lon="75.8640407" version="1"> 
     <tag k="name" v="Tathgar Jathere" /> 
     <tag k="amenity" v="place_of_worship" /> 
     <tag k="religion" v="sikh" /> 
     <tag k="denomination" v="Devotees of Baba Namdev" /> 
    </node>