如何读取URL的XML数据

如何读取URL的XML数据

本文介绍了安卓:如何读取URL的XML数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要读URL的XML数据,并以不同的方式都试过了。但无法找到答案。亚姆开发agumented现实应用,从XML(这是采用URL),其中IAM读取位置信息

荫新蜂到Android以及

我有以下的XML数据。

 < specialoffers>
<类别和GT;
<类别及GT;
      <![CDATA [0%分期付款计划信息]>
< /类别>
<&商人GT;
     <&MERCHANTNAME GT;
             <![CDATA [EmaxIPP]>
     < / MERCHANTNAME>
     < merchantbigimage>
             <![CDATA [
             http://www.XXX.com/Images/Emax%20New%20-%20190x73-1_tcm20-48180.jpg
      ]]>
     < / merchantbigimage>
     < merchantsmallimage>
             <![CDATA [
             http://www.XXX.com/Images/Emax%20New%20-%20104x75-1_tcm20-48179.jpg
              ]]>
             < / merchantsmallimage>
     < merchantmobileimage>
             <![CDATA [http://www.XXX.com]>
     < / merchantmobileimage>
     < mobilehighlight>
             <![CDATA [
            享受0%分期付款计划3个月
            所有购买制作和LT; / B>
            ]]>
     < / mobilehighlight>
     <高亮>
            <![CDATA [
            享受0%分期付款计划对所有购买3个月
            使用&lt作出; / B>
            ]]>
      < /高光>
     <地点和GT;
          <地点>
               <&酋长国GT;
                   <![CDATA [XXX]]>
               < /迪拜>
               <地址>
                   <![CDATA [中央1]>
               < /地址>
               <纬度和GT;
                   <![CDATA [51.169601]>
              < /纬度和GT;
              <经度>
                   <![CDATA [61.240395]>
              < /经度>
          < /地点>
     < /客商与GT;   < /类别和GT;
< / specialoffers>

下面是code ....

AndroidXMLParsingActivity.java

 公共类AndroidXMLParsingActivity扩展ListActivity {//所有静态变量
静态最终字符串URL =htt​​p://www.adcb.com/specialoffers-test.xml;
// XML节点键
静态最后弦乐KEY_ITEM =类别; //父节点
静态最后弦乐KEY_ID =类别;
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main);ArrayList的<&HashMap的LT;字符串,字符串>>菜单项=
                                 新的ArrayList<&HashMap的LT;字符串,字符串>>();XMLParser的解析器=新XMLParser的();
字符串XML = parser.getXmlFromUrl(URL); //获取XML文档的文档= parser.getDomElement(XML); //获得DOM元素节点列表NL = doc.getElementsByTagName(KEY_ITEM);
项目> //遍历所有项目节点&LT循环;
的for(int i = 0; I< nl.getLength();我++){
    //创建新的HashMap
    HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>();
    元素e =(元)nl.item(I)
    //将每个子节点的HashMap键=>值
    map.put(KEY_ID,parser.getValue(即KEY_ID));
    //添加HashList到ArrayList的
    menuItems.add(地图);
}//添加菜单项到ListView控件
ListAdapter适配器=新SimpleAdapter(这一点,菜单项,
        R.layout.list_item,
        新的String [] {KEY_ID,KEY_DESC,100},新的INT [] {
                R.id.name,R.id.desciption,R.id.cost});setListAdapter(适配器);//选择单个ListView项
ListView控件LV = getListView();lv.setOnItemClickListener(新OnItemClickListener(){    @覆盖
    公共无效onItemClick(适配器视图<>母公司,观景,
            INT位置,长的id){
        //从选定的ListItem得到的值
        字符串名称=((TextView中)
                                  view.findViewById(R.id.name))的getText()的toString()。
        串成本=((TextView中)
                                   view.findViewById(R.id.cost))的getText()的toString()。
        字符串描述=((TextView中)
                              view.findViewById(R.id.desciption))的getText()的toString()。        //开始新意图
        在意向=新意图(getApplicationContext()
                                    SingleMenuItemActivity.class);
        in.putExtra(KEY_ID,名);
        in.putExtra(100,成本);
        in.putExtra(KEY_DESC,说明);
        startActivity(在);    }
});
}
}

XMLParser.java

 公共XMLParser类{//构造
公共XMLParser的(){}/ **
 *从URL获取XML使得HTTP请求
 * @参数的URL字符串
 * * /
公共字符串getXmlFromUrl(字符串URL){
    字符串XML = NULL;    尝试{
        // defaultHttpClient
        DefaultHttpClient的HttpClient =新DefaultHttpClient();
        HttpPost httpPost =新HttpPost(URL);        HTT presponse HTT presponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = HTT presponse.getEntity();
        XML = EntityUtils.toString(httpEntity);    }赶上(UnsupportedEncodingException五){
        e.printStackTrace();
    }赶上(ClientProtocolException E){
        e.printStackTrace();
    }赶上(IOException异常五){
        e.printStackTrace();
    }
    //返回XML
    返回XML;
}/ **
 *获取XML DOM元素
 * @参数XML字符串
 * * /
公开文件getDomElement(字符串XML){
    文档DOC = NULL;
    DBF的DocumentBuilderFactory = DocumentBuilderFactory.newInstance();
    尝试{        的DocumentBuilder分贝= dbf.newDocumentBuilder();        InputSource的是=新的InputSource();
            is.setCharacterStream(新StringReader(XML));
            DOC = db.parse(是);        }赶上(的ParserConfigurationException E){
            Log.e(错误,e.getMessage());
            返回null;
        }赶上(SAXException的E){
            Log.e(错误,e.getMessage());
            返回null;
        }赶上(IOException异常五){
            Log.e(错误,e.getMessage());
            返回null;
        }        返回文档;
}/ **获取节点值
  * @参数ELEM元素
  * /
 公共最后弦乐getElementValue(节点ELEM){
     子节点;
     如果(ELEM!= NULL){
         如果(elem.hasChildNodes()){
             对于(孩子= elem.getFirstChild(!);孩子= NULL;儿童=
child.getNextSibling()){
                 如果(child.getNodeType()== Node.TEXT_NODE){
                     返回child.getNodeValue();
                 }
             }
         }
     }
     返回;
 } / **
  *获取节点值
  * @参数Element节点
  * @参数密钥字符串
  * * /
 公共字符串的getValue(元素项,字符串str){
        节点列表N = item.getElementsByTagName(STR);
        返回this.getElementValue(n.item(0));
    }
}

SingleMenuItemActivity.java

 公共类SingleMenuItemActivity延伸活动{// XML节点键
静态最后弦乐KEY_ID =类别;
静态最后弦乐KEY_COST =成本;
静态最后弦乐KEY_DESC =说明;
@覆盖
    公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.single_list_item);    //获取数据的意图
    在意向= getIntent();    //从previous意图XML值
    字符串名称= in.getStringExtra(KEY_ID);
    串成本= in.getStringExtra(KEY_COST);
    字符串描述= in.getStringExtra(KEY_DESC);    //在屏幕上显示的所有值
    TextView的lblName =(的TextView)findViewById(R.id.name_label);
    TextView的lblCost =(的TextView)findViewById(R.id.cost_label);
    TextView的lblDesc =(的TextView)findViewById(R.id.description_label);    lblName.setText(名);
    lblCost.setText(成本);
    lblDesc.setText(介绍);
}
}


解决方案

使用的 XML解析API为Android它会让你的编码很容易。

I want to read XML data from URL and have tried in different ways. But unable to find the answer. Iam developing a agumented reality application, where iam reading location information from XML ( which is in URL )

Iam new bee to android as well

I have the following XML data.

<specialoffers>
<categories>
<category>
      <![CDATA[ 0% Installment Payment Plan Offers ]]>
</category>
<merchants>
     <merchantname>
             <![CDATA[ EmaxIPP ]]>
     </merchantname>
     <merchantbigimage>
             <![CDATA[
             http://www.XXX.com/Images/Emax%20New%20-%20190x73-1_tcm20-48180.jpg
      ]]>
     </merchantbigimage>
     <merchantsmallimage>
             <![CDATA[
             http://www.XXX.com/Images/Emax%20New%20-%20104x75-1_tcm20-48179.jpg
              ]]>
             </merchantsmallimage>
     <merchantmobileimage>
             <![CDATA[ http://www.XXX.com ]]>
     </merchantmobileimage>
     <mobilehighlight>
             <![CDATA[
            Enjoy 0% Installment Payment Plan for 3 months on
            all purchases made </b>
            ]]>
     </mobilehighlight>
     <highlight>
            <![CDATA[
            Enjoy 0% Installment Payment Plan for 3 months on all purchases
            made with  your </b>
            ]]>
      </highlight>
     <locations>
          <location>
               <emirate>
                   <![CDATA[ XXX]]>
               </emirate>
               <address>
                   <![CDATA[ Center 1 ]]>
               </address>
               <latitude>
                   <![CDATA[ 51.169601 ]]>
              </latitude>
              <longitude>
                   <![CDATA[ 61.240395 ]]>
              </longitude>
          </location>
     </merchants>

   </categories>
</specialoffers>

Here is the code....

AndroidXMLParsingActivity.java

public class AndroidXMLParsingActivity extends ListActivity {

// All static variables
static final String URL = "http://www.adcb.com/specialoffers-test.xml";
// XML node keys
static final String KEY_ITEM = "categories"; // parent node
static final String KEY_ID = "category";


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

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

XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML

Document doc = parser.getDomElement(xml); // getting DOM element

NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// 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_ID, parser.getValue(e, KEY_ID));
    // adding HashList to ArrayList
    menuItems.add(map);
}

// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
        R.layout.list_item,
        new String[] { KEY_ID, "KEY_DESC", "100" }, new int[] {
                R.id.name, R.id.desciption, R.id.cost });

setListAdapter(adapter);

// selecting single ListView item
ListView lv = getListView();

lv.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
        // getting values from selected ListItem
        String name = ((TextView)
                                  view.findViewById(R.id.name)).getText().toString();
        String cost = ((TextView)
                                   view.findViewById(R.id.cost)).getText().toString();
        String description = ((TextView)
                              view.findViewById(R.id.desciption)).getText().toString();

        // Starting new intent
        Intent in = new Intent(getApplicationContext(),
                                    SingleMenuItemActivity.class);
        in.putExtra(KEY_ID, name);
        in.putExtra("100", cost);
        in.putExtra("KEY_DESC", description);
        startActivity(in);

    }
});
}
}

XMLParser.java

public class XMLParser {

// constructor
public XMLParser() {

}

/**
 * Getting XML from URL making HTTP request
 * @param url string
 * */
public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        xml = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // return XML
    return xml;
}

/**
 * Getting XML DOM element
 * @param XML string
 * */
public Document getDomElement(String xml){
    Document doc = null;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {

        DocumentBuilder db = dbf.newDocumentBuilder();

        InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is);

        } catch (ParserConfigurationException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (IOException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        }

        return doc;
}

/** Getting node value
  * @param elem element
  */
 public final String getElementValue( Node elem ) {
     Node child;
     if( elem != null){
         if (elem.hasChildNodes()){
             for( child = elem.getFirstChild(); child != null; child =
child.getNextSibling() ){
                 if( child.getNodeType() == Node.TEXT_NODE  ){
                     return child.getNodeValue();
                 }
             }
         }
     }
     return "";
 }

 /**
  * Getting node value
  * @param Element node
  * @param key string
  * */
 public String getValue(Element item, String str) {
        NodeList n = item.getElementsByTagName(str);
        return this.getElementValue(n.item(0));
    }
}

SingleMenuItemActivity.java

public class SingleMenuItemActivity  extends Activity {

// XML node keys
static final String KEY_ID = "category";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
@Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_list_item);

    // getting intent data
    Intent in = getIntent();

    // Get XML values from previous intent
    String name = in.getStringExtra(KEY_ID);
    String cost = in.getStringExtra(KEY_COST);
    String description = in.getStringExtra(KEY_DESC);

    // Displaying all values on the screen
    TextView lblName = (TextView) findViewById(R.id.name_label);
    TextView lblCost = (TextView) findViewById(R.id.cost_label);
    TextView lblDesc = (TextView) findViewById(R.id.description_label);

    lblName.setText(name);
    lblCost.setText(cost);
    lblDesc.setText(description);
}
}
解决方案

Use SimpleXml xml parsing API for android it'll make your coding easy.

这篇关于安卓:如何读取URL的XML数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 06:38