使用SAX进行Android XML解析

时间:2014-01-09 12:41:46

标签: android xml parsing sax

我正在尝试解析这个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>

但不明白我怎么能得到ccy,ccy_name_ru ......和其他attr。

我早期正在解析这个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>

我使用此代码执行此操作:

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;
    }

但我不知道如何使用我的新xml,但这样做? 有人可以解释一下这件事吗?

2 个答案:

答案 0 :(得分:0)

事物ccy,ccy_name被称为属性。

现在在SAX解析器中你有以下方法

//opening element tag
public void startElement (String uri, String name, String qName, Attributes atts)
{
    //handle the start of an element
}

您将收到Attributes atts个参数中的所有属性。

你可以在下面写下代码来获取ccv String strccv = atts.getValue(“ccv”);

理想情况下,您的回答应该是

<exchangerates>
<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"/>
</exchangerates>

我们有不同的父标签与交换率和带有交换的子标签

答案 1 :(得分:0)

首先,你在彼此内部有相同的标签。这是一个错误,您必须更改外部标记名称,如<exchangerates>。你可以读取这样的标签的属性:

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)); 
    }
}