安卓:标签RSS源解析 [英] Android:tags for RSS feed parsing

查看:116
本文介绍了安卓:标签RSS源解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的RSS提要IM试图解析

 < PetrolPrices>
<燃料类型=无铅>
<最高单位=P>&132.9 LT; /最高>
<平均单位=P>&128.8 LT; /平均>
<最低的单位=P>&125.9 LT; /最低>
< /燃油>
<燃料类型=柴油>
<最高单位=P>&137.9 LT; /最高>
<平均单位=P>&132.4 LT; /平均>
<最低的单位=P>&129.7 LT; /最低>
< /燃油>
<燃料类型=超级无铅>
<最高单位=P>&142.9 LT; /最高>
<平均单位=P>&137.7 LT; /平均>
<最低的单位=P>&132.9 LT; /最低>
< /燃油>
< LINK>
http://www.petrolprices.com/search.html?search=Glasgow
< / LINK>
< / PetrolPrices>

问题是这是从任何XML香港专业教育学院以往任何时候都解析我的意思是大部分的时间非常不同的一个简单的

 <标题>
标题
< /标题>

我的问题是什么,我应该使用标记名称,也怎么可能拿到燃料标记,因为其时,即时通讯试图让其它标记使用。基本上,我希望它解析像下面

 类型是=无铅
       最高单位= 132.9
       平均单位= 128.8
       最低单位= 125.9

*在所有其他标记完成

 链接= http://www.petrolprices.com/feeds/averages.xml?search_type=town&search_value=glasgow

编辑:这是code I用于分析数据

 包org.me.myandroidstuff;进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.net.HttpURLConnection中;
进口java.net.MalformedURLException;
进口的java.net.URL;
进口java.net.URLConnection中;
进口的java.util.ArrayList;
进口的java.util.HashMap;进口org.w3c.dom.Document中;
进口org.w3c.dom.Element中;
进口org.w3c.dom.NodeList;进口android.app.ListActivity;
进口android.app.ProgressDialog;
进口android.os.AsyncTask;
//进口android.app.Activity;
进口android.os.Bundle;
进口android.util.Log;
进口android.widget.ListAdapter;
//进口android.widget.ListView;
进口android.widget.SimpleAdapter;
进口android.widget.TextView;公共类PetrolPriceActivity扩展ListActivity
{
    静态最后弦乐KEY_FUEL =燃料; //父节点
    静态最后弦乐为key_type =类型;
    静态最后弦乐KEY_HIGHEST =最高;
    静态最后弦乐KEY_AVERAGE =平​​均值;
    静态最后弦乐KEY_LOWEST =最低;
    私人TextView的ERRORTEXT;
    私人字符串petrolPriceURL;
    私有静态最后弦乐TAG =PetrolPrice;
    / **当第一次创建活动调用。 * /
    @覆盖
    公共无效的onCreate(捆绑savedInstanceState)
    {        super.onCreate(savedInstanceState);
        的setContentView(R.layout.list);        捆绑额外= getIntent()getExtras()。
        如果(临时演员!= NULL){
        petrolPriceURL = extras.getString(URLString);        }
        //获取显示结果上TextView的对象
        新的AsyncTask()执行(petrolPriceURL);     }    //的onCreate结束
公共类AsyncTask的扩展的AsyncTask<字符串,整数的ArrayList<&HashMap的LT;字符串,字符串>>>{
        ArrayList的<&HashMap的LT;字符串,字符串>>菜单项;
        ProgressDialog对话框=新ProgressDialog(PetrolPriceActivity.this);        @覆盖
           在preExecute保护无效()
        {
          dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
          dialog.setProgress(0);
          dialog.setMax(100);
          dialog.setMessage(载入中...);
          dialog.show();
        }        @覆盖
        保护的ArrayList<&HashMap的LT;字符串,字符串>> doInBackground(字符串... PARAMS)        {            的for(int i = 0; I< 100;我++)
           {
                publishProgress(1);
                尝试
                {
                    视频下载(50);
                }
                赶上(InterruptedException的E)
                {
                    // TODO自动生成catch块
                    e.printStackTrace();
                }
            }
            字符串urlString = petrolPriceURL;
            字符串结果=;
            InputStream的anInStream = NULL;
            INT响应= -1;
            网址URL = NULL;            尝试
            {
                URL =新的URL(urlString);
            }
            赶上(MalformedURLException的E)
            {
                // TODO自动生成catch块
                返回null;
            }            康涅狄格州的URLConnection = NULL;
            尝试
            {
                康恩= url.openConnection();
            }
            赶上(IOException异常E)
            {
                // TODO自动生成catch块
                返回null;
            }            //检查连接可以打开
            如果(!(康涅狄格州的instanceof HttpURLConnection类))
            {
                尝试
                {
                    抛出新IOException异常(不是一个HTTP连接);
                }
                赶上(IOException异常E)
                {
                    // TODO自动生成catch块
                    返回null;
                }
            }            尝试
            {
                //打开连接
                HttpURLConnection的httpConn =(HttpURLConnection类)美国康涅狄格州;
                httpConn.setAllowUserInteraction(假);
                httpConn.setInstanceFollowRedirects(真);
                httpConn.setRequestMethod(GET);
                httpConn.connect();
                响应= httpConn.getResponse code();
                //检查连接正常
                如果(响应== HttpURLConnection.HTTP_OK)
                {
                    //连接可以这么打开阅读器
                    anInStream = httpConn.getInputStream();
                    InputStreamReader的在=新的InputStreamReader(anInStream);
                    的BufferedReader斌=新的BufferedReader(中);                    //读取数据从RSS流
                    串线=新的String();
                    而(((行= bin.readLine()))!= NULL)
                    {                        结果=结果+线;
                    }
                }                        菜单项=新的ArrayList<&HashMap的LT;字符串,字符串>>();                        处理程序分析器=新的处理程序();
                        字符串XML =结果; //获取XML
                        文档的文档= parser.getDomElement(XML);
                        //获得DOM元素                        节点列表NL = doc.getElementsByTagName(KEY_FUEL);
                        Log.v(TAG,索引=+ nl.getLength());                        项目> //遍历所有项目节点&LT循环;
                        的for(int i = 0; I< nl.getLength();我++)
                        {
                            //创建新的HashMap
                            HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
                            元素e =(元)nl.item(I)
                            //将每个子节点的HashMap键=>值
                            map.put(key_type的,parser.getValue(即,为key_type));
                            map.put(KEY_HIGHEST,最高单位=+ parser.getValue(即KEY_HIGHEST));
                            map.put(KEY_AVERAGE,平均单位=+ parser.getValue(即KEY_AVERAGE));
                            map.put(KEY_LOWEST,最低单位=+ parser.getValue(即KEY_LOWEST));                            //添加HashList到ArrayList的
                            menuItems.add(地图);
                            Log.v(TAG,指数1 =+菜单项);
                        }
            }
            赶上(IOException异常前)
            {
                尝试
                {
                    抛出新IOException异常(错误连接);                }
                赶上(IOException异常E)
                {
                    // TODO自动生成catch块
                    e.printStackTrace();
                }             }
            返回菜单项;           }
           @覆盖           保护无效onProgressUpdate(整数...进度)
           {               dialog.incrementProgressBy(进展[0]);
           }           @覆盖
           保护无效onPostExecute(ArrayList的<&HashMap的LT;字符串,字符串>>菜单项)
           {               ERRORTEXT =(的TextView)findViewById(R.id.error);
               TextView的linkView =(的TextView)findViewById(R.id.link);
               尝试
                {
                   //取得从RSS流中的数据作为串
                   ListAdapter适配器=新SimpleAdapter(PetrolPriceActivity.this,菜单项,
                   R.layout.list_content,                   新的String [] {key_type的,KEY_HIGHEST,KEY_AVERAGE,KEY_LOWEST},新的INT [] {
                   R.id.fuel,R.id.highest,R.id.average,R.id.lowest});                   Log.v(TAG,索引2 =+菜单项);                   setListAdapter(适配器);
                }
                赶上(例外AE)
                {
                    //处理错误
                    //添加错误信息要记录的诊断
                    errorText.setText(ae.toString());
                }
                linkView.setText(petrolPriceURL);
                Log.v(TAGindexppu =+ petrolPriceURL);                如果(dialog.getProgress()== dialog.getMax())
                dialog.dismiss();          }}
    // petrolPriceString结束
 // Activity类的结束
}


解决方案

试试这个..

使用XMLPullParser

  {尝试        网址URL =新的URL(
                http://www.petrolprices.com/feeds/averages.xml?search_type=town&search_value=glasgow);
        DBF的DocumentBuilderFactory = DocumentBuilderFactory.newInstance();
        的DocumentBuilder分贝= dbf.newDocumentBuilder();
        文档的文档= db.parse(新的InputSource(url.openStream()));
        doc.getDocumentElement()正常化()。        节点列表节点列表= doc.getElementsByTagName(燃料);        的for(int i = 0; I< nodeList.getLength();我++){            元件nameElement1 =(元件)nodeList.item(ⅰ);            的System.out.println(类型:+ nameElement1.getAttribute(类型)); //这里我们得到的类型属性值            Toast.makeText(getBaseContext(),TYPE =
                    + nameElement1.getAttribute(类型),Toast.LENGTH_SHORT).show();            节点node = nodeList.item(ⅰ);            元素fstElmnt =(元素)节点;
            节点列表名称列表= fstElmnt.getElementsByTagName(最高);
            元件nameElement =(元件)nameList.item(0);
            NAMELIST = nameElement.getChildNodes();            Toast.makeText(getBaseContext(),最高=
                    +((节点)nameList.item(0))getNodeValue(),Toast.LENGTH_SHORT).show();            Log.v(Highest--,((节点)nameList.item(0))getNodeValue());            节点列表websiteList = fstElmnt.getElementsByTagName(平均值);
            元件websiteElement =(元件)websiteList.item(0);
            websiteList = websiteElement.getChildNodes();            Log.v(Average--,((节点)websiteList.item(0))getNodeValue());            websiteList = fstElmnt.getElementsByTagName(最低);
            websiteElement =(元件)websiteList.item(0);
            websiteList = websiteElement.getChildNodes();            Log.v(Lowest--,((节点)websiteList.item(0))getNodeValue());        }
    }赶上(例外五){
        的System.out.println(XML帕兴错误时抛出=+ e)条;
    }

修改

更改这个..

  map.put(key_type的,parser.getValue(即,为key_type));

  map.put(key_type的,e.getAttribute(为key_type));

Here is my RSS feed im trying to parse

<PetrolPrices>
<Fuel type="Unleaded">
<Highest units="p">132.9</Highest>
<Average units="p">128.8</Average>
<Lowest units="p">125.9</Lowest>
</Fuel>
<Fuel type="Diesel">
<Highest units="p">137.9</Highest>
<Average units="p">132.4</Average>
<Lowest units="p">129.7</Lowest>
</Fuel>
<Fuel type="Super Unleaded">
<Highest units="p">142.9</Highest>
<Average units="p">137.7</Average>
<Lowest units="p">132.9</Lowest>
</Fuel>
<Link>
http://www.petrolprices.com/search.html?search=Glasgow
</Link>
</PetrolPrices>

the problem is this is very different from any xml ive ever parsed i mean most of the time its a simple

<title>
"The Title"
</title>

My question is which what are the tag names i should be using and also how is it possible to get the fuel tag since its used when im trying to get the other tags. Basically i want it parsed like below

Type is = "Unleaded
       Highest units = 132.9
       Average units = 128.8
       Lowest units = 125.9

*after all other tags are done

link = http://www.petrolprices.com/feeds/averages.xml?search_type=town&search_value=glasgow

Edit: this is the code i use to parse the data

    package org.me.myandroidstuff;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
//import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
//import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class PetrolPriceActivity extends ListActivity 
{
    static final String KEY_FUEL = "Fuel"; // parent node
    static final String KEY_TYPE = "type";
    static final String KEY_HIGHEST = "Highest";
    static final String KEY_AVERAGE = "Average";
    static final String KEY_LOWEST = "Lowest";
    private TextView errorText;
    private String petrolPriceURL;
    private static final String TAG = "PetrolPrice";


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);

        Bundle extras = getIntent().getExtras();
        if(extras!=null){
        petrolPriceURL =extras.getString("URLString");

        }
        // Get the TextView object on which to display the results
        new asyncTask().execute(petrolPriceURL);

     }

    // End of onCreate


public class asyncTask extends AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> 

{
        ArrayList<HashMap<String, String>> menuItems;
        ProgressDialog dialog = new ProgressDialog(PetrolPriceActivity.this);

        @Override
           protected void onPreExecute() 
        {
          dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
          dialog.setProgress(0);
          dialog.setMax(100);
          dialog.setMessage("loading...");
          dialog.show();
        }

        @Override
        protected ArrayList<HashMap<String, String>> doInBackground(String...params) 

        {

            for(int i = 0; i < 100; i++) 
           {
                publishProgress(1);
                try 
                {
                    Thread.sleep(50);
                }
                catch (InterruptedException e) 
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }


            String urlString = petrolPriceURL;
            String result = "";
            InputStream anInStream = null;
            int response = -1;
            URL url = null;

            try 
            {
                url = new URL(urlString);
            } 
            catch (MalformedURLException e) 
            {
                // TODO Auto-generated catch block
                return null;
            }

            URLConnection conn = null;
            try 
            {
                conn = url.openConnection();
            } 
            catch (IOException e) 
            {
                // TODO Auto-generated catch block
                return null;
            }

            // Check that the connection can be opened
            if (!(conn instanceof HttpURLConnection)) 
            {
                try 
                {
                    throw new IOException("Not an HTTP connection");
                } 
                catch (IOException e) 
                {
                    // TODO Auto-generated catch block
                    return null;
                }
            }

            try 
            {
                // Open connection
                HttpURLConnection httpConn = (HttpURLConnection) conn;
                httpConn.setAllowUserInteraction(false);
                httpConn.setInstanceFollowRedirects(true);
                httpConn.setRequestMethod("GET");
                httpConn.connect();
                response = httpConn.getResponseCode();
                // Check that connection is OK
                if (response == HttpURLConnection.HTTP_OK) 
                {
                    // Connection is OK so open a reader
                    anInStream = httpConn.getInputStream();
                    InputStreamReader in= new InputStreamReader(anInStream);
                    BufferedReader bin= new BufferedReader(in);

                    // Read in the data from the RSS stream
                    String line = new String();
                    while (( (line = bin.readLine())) != null)
                    {

                        result = result + line;
                    }
                }

                        menuItems = new ArrayList<HashMap<String, String>>();

                        Handler parser = new Handler();
                        String xml = result; // getting XML
                        Document doc = parser.getDomElement(xml);


                        // getting DOM element

                        NodeList nl = doc.getElementsByTagName(KEY_FUEL);
                        Log.v(TAG, "index=" + nl.getLength());

                        // looping through all item nodes <item>
                        for (int i = 0; i < nl.getLength(); i++) 
                        {
                            // creating new HashMap
                            HashMap<String, String> map = new HashMap<String, String>();
                            Element e = (Element) nl.item(i);
                            // adding each child node to HashMap key => value
                            map.put(KEY_TYPE, parser.getValue(e, KEY_TYPE));
                            map.put(KEY_HIGHEST, "Highest units = " + parser.getValue(e, KEY_HIGHEST));
                            map.put(KEY_AVERAGE, "Average units = " + parser.getValue(e, KEY_AVERAGE));
                            map.put(KEY_LOWEST, "Lowest units = " +parser.getValue(e, KEY_LOWEST));

                            // adding HashList to ArrayList
                            menuItems.add(map);
                            Log.v(TAG, "index1=" + menuItems);
                        }
            }


            catch (IOException ex) 
            {
                try 
                {
                    throw new IOException("Error connecting");

                } 
                catch (IOException e) 
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

             }
            return menuItems;

           }
           @Override

           protected void onProgressUpdate(Integer...progress)
           {

               dialog.incrementProgressBy(progress[0]);
           }

           @Override
           protected void onPostExecute(ArrayList<HashMap<String,String>> menuItems) 
           {

               errorText = (TextView)findViewById(R.id.error);
               TextView linkView = (TextView)findViewById(R.id.link);


               try
                {
                   //Get the data from the RSS stream as a string
                   ListAdapter adapter = new SimpleAdapter(PetrolPriceActivity.this, menuItems,
                   R.layout.list_content,

                   new String[] { KEY_TYPE, KEY_HIGHEST, KEY_AVERAGE, KEY_LOWEST}, new int[] {
                   R.id.fuel, R.id.highest, R.id.average, R.id.lowest});

                   Log.v(TAG, "index2=" + menuItems);



                   setListAdapter(adapter);


                }
                catch(Exception ae)
                {
                    // Handle error
                    // Add error info to log for diagnostics
                    errorText.setText(ae.toString());
                } 
                linkView.setText(petrolPriceURL);
                Log.v(TAG, "indexppu=" + petrolPriceURL);

                if(dialog.getProgress() == dialog.getMax())
                dialog.dismiss();

          }

}
    // End of petrolPriceString
 // End of Activity class
}

解决方案

Try this..

Use XMLPullParser

    try {

        URL url = new URL(
                "http://www.petrolprices.com/feeds/averages.xml?search_type=town&search_value=glasgow");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new InputSource(url.openStream()));
        doc.getDocumentElement().normalize();

        NodeList nodeList = doc.getElementsByTagName("Fuel");

        for (int i = 0; i < nodeList.getLength(); i++) {

            Element nameElement1 = (Element) nodeList.item(i);

            System.out.println("type : "+ nameElement1.getAttribute("type"));        // Here we are getting type Attribute Value

            Toast.makeText(getBaseContext(), "type = "
                    + nameElement1.getAttribute("type"), Toast.LENGTH_SHORT).show();

            Node node = nodeList.item(i);

            Element fstElmnt = (Element) node;
            NodeList nameList = fstElmnt.getElementsByTagName("Highest");
            Element nameElement = (Element) nameList.item(0);
            nameList = nameElement.getChildNodes();

            Toast.makeText(getBaseContext(), "Highest = "
                    + ((Node) nameList.item(0)).getNodeValue(), Toast.LENGTH_SHORT).show();

            Log.v("Highest--", ((Node) nameList.item(0)).getNodeValue());

            NodeList websiteList = fstElmnt.getElementsByTagName("Average");
            Element websiteElement = (Element) websiteList.item(0);
            websiteList = websiteElement.getChildNodes();

            Log.v("Average--", ((Node) websiteList.item(0)).getNodeValue());

            websiteList = fstElmnt.getElementsByTagName("Lowest");
            websiteElement = (Element) websiteList.item(0);
            websiteList = websiteElement.getChildNodes();

            Log.v("Lowest--", ((Node) websiteList.item(0)).getNodeValue());

        }
    } catch (Exception e) {
        System.out.println("XML Pasing Excpetion = " + e);
    }

EDIT

Change this..

map.put(KEY_TYPE, parser.getValue(e, KEY_TYPE));

to

map.put(KEY_TYPE, e.getAttribute(KEY_TYPE));

这篇关于安卓:标签RSS源解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆