Search code examples
androidxmlparsingsax

Android XML parsing using SAX


I'm trying to parse this xml:

<exchangerate>
<exchangerate ccy="AMD" ccy_name_ru="Армянский драм " ccy_name_ua="Вiрменський драм " ccy_name_en="Armenian Dram " base_ccy="RU" buy="805393" unit="1000.00000" date="2014.01.09"/>
<exchangerate ccy="AUD" ccy_name_ru="Австралийский доллар " ccy_name_ua="Австралiйський долар " ccy_name_en="Australian Dollar " base_ccy="RU" buy="291544" unit="1.00000" date="2014.01.09"/>
</exchangerate>

But cannt understand how can i get ccy, ccy_name_ru... and other attr.

Early i'm parsing this xml:

<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" version="2.0">
<channel>
<atom:link href="http://dengi-banki-kredit.webnode.ru/rss/novosti.xml" rel="self" type="application/rss+xml"/>
<title>
<![CDATA[ Новости - dengi-banki-kredit.webnode.ru ]]>
</title>
<link>http://dengi-banki-kredit.webnode.ru</link>
<language>ru</language>
<pubDate>Fri, 11 Jan 2013 07:25:00 +0100</pubDate>
<lastBuildDate>Fri, 11 Jan 2013 07:25:00 +0100</lastBuildDate>
<category>
<![CDATA[ Новости ]]>
</category>
<docs>http://blogs.law.harvard.edu/tech/rss</docs>
<generator>Webnode</generator>
<item>
<title>
<![CDATA[
Росбанк провел новогоднюю благотворительную акцию в поддержку детей
]]>
</title>
<link>
http://dengi-banki-kredit.webnode.ru/news/rosbank-provjel-novogodnjuju-blagotvoritjelnuju-aktsiju-v-poddjerzhku-djetjej/
</link>
<description>
<![CDATA[
Сотрудники Росбанка в рамках базара могли приобрести оригинальные новогодние сувениры, сделанные детьми-сиротами и молодыми людьми с ограниченными возможностями, говорится в сообщении кредитной организации. &nbsp; В базаре приняли участие общественная организация «Художественный центр «Дети Марии», благотворительный проект «Социальные метры», межрегиональная общественная организация помощи детям с особенностями развития и их семьям «Дорога в мир», Центр равных возможностей «Вверх» и свои...
]]>
</description>
<pubDate>Fri, 11 Jan 2013 07:25:00 +0100</pubDate>
<guid isPermaLink="true">
http://dengi-banki-kredit.webnode.ru/news/rosbank-provjel-novogodnjuju-blagotvoritjelnuju-aktsiju-v-poddjerzhku-djetjej/
</guid>
<category>Новости</category>
</item>

I do it with this code:

public class Parser {

    public static String url = null;

    class MyTask extends AsyncTask<String, Void, List<PostItem>> {

        @Override
        protected List<PostItem> doInBackground(String... params) {
            URL feedUrl;
            InputStream is = null;

            try {
                feedUrl = new URL(url);
                is = feedUrl.openConnection().getInputStream();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            final PostItem currentPost = new PostItem();
            final List<PostItem> messages = new ArrayList<PostItem>();
            RootElement root = new RootElement("rss");
            Element channel = root.getChild("channel");
            Element item = channel.getChild("item");
            item.setEndElementListener(new EndElementListener() {
                public void end() {
                    messages.add(currentPost.copy());
                }
            });
            item.getChild("title").setEndTextElementListener(
                    new EndTextElementListener() {
                        public void end(String body) {
                            currentPost.setTitle(body);
                        }
                    });
            item.getChild("link").setEndTextElementListener(
                    new EndTextElementListener() {
                        public void end(String body) {
                            currentPost.setLink(body);
                        }
                    });
            item.getChild("description").setEndTextElementListener(
                    new EndTextElementListener() {
                        public void end(String body) {
                            currentPost.setDescription(body);
                        }
                    });
            item.getChild("pubDate").setEndTextElementListener(
                    new EndTextElementListener() {
                        public void end(String body) {
                            currentPost.setDate(body);
                        }
                    });
            try {
                Xml.parse(is, Xml.Encoding.UTF_8, root.getContentHandler());
            } catch (Exception e) {
                Log.d("MyTag", e.toString());
            }
            return messages;
        }
    }

    public List<PostItem> parse() {
        List<PostItem> result = null;
        MyTask mt = new MyTask();
        try {
            result = mt.execute("").get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return result;
    }

But i dont know how to do it with my new xml but in such way ? Anybody can explain me this thing ?


Solution

  • first of all you have same tags inside each other. That is a mistake, you have to change the outer tag name like <exchangerates>. you can read attributes of a tag like this:

    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        if (qName.equals("exchangerate")) {
                     map.put("ccy", attributes.getValue(0)); 
                     map.put("ccy_name_ru", attributes.getValue(1)); 
                     map.put("ccy_name_ua", attributes.getValue(2)); 
                     map.put("ccy_name_en", attributes.getValue(3)); 
                     map.put("base_ccy", attributes.getValue(4)); 
                     map.put("buy", attributes.getValue(5)); 
                     map.put("unit", attributes.getValue(6)); 
                     map.put("date", attributes.getValue(7)); 
        }
    }