简体   繁体   中英

android sax xml parsing with multiple parent

I am trying to parse data from a xml page through sax parsing technique.The structure of the xml page is

<?xml version="1.0" encoding="UTF-8"?>
<news_magazine>
    <latest_news>
        <news>
            <category_id>5</category_id>
            <author>Super Admin</author>
        </news>
        <news>
            <category_id>6</category_id>
            <author>user</author>
        </news>
    </latest_news>
    <categories>
        <category>
            <category_id>5</category_id>
            <category_name>cricket</category_name>
        </category>
        <category>
            <category_id>5</category_id>
            <category_name>cricket</category_name>
        </category>
    </categories>
</news_magazine>

Both the news tag and category tag contains category id.How can i take the the category id separately?

Hey you can do this in very simple way. Just maintain a extra variable when you put conditions in the parser when you get any of "news" or "category" tag than assign that in current_parent. and when comparing the tag "category_id" than also put condition of current_parent

public static String current_parent;
public void startElement(String namespaceURI, String localName, 
            String qName, Attributes atts) {
    if (localName.equals("news") {
          current_parent = "news";
        // Do your code with news.
        return;
    }
    else  if (localName.equals("category") {
          current_parent = "category";
        // Do your code with category.
        return;
    }
     else  if (localName.equals("category_id") {
         if(current_parent.equals("category")
            {
        // Do your code with category's category_id.
             }else if(current_parent.equals("news")
               {
        // Do your code with news's category_id.
             }
        return;
    }
}

Consider to use databinding of your choice and pull parser. This task will be no-brainer with (say) xstream or jackson. IN case you really like to do it manually, use pull parser ( you no longer receive callbacks, but actively pull elements ) - this adapts better to java programm flow

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM