Some words about me

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas a urna sit amet leo sagittis cursus a at lectus. Donec bibendum facilisis ultricies. Maecenas nec arcu dui, ut lobortis erat. In nec condimentum quam. Vivamus euismod scelerisque ligula vitae fermentum. Nulla dignissim rutrum eleifend.

Donec mi eros, congue ut consectetur eget, pretium vitae orci. Aliquam pharetra ultricies lobortis. Morbi eget nisi lectus. Maecenas felis augue, molestie in vestibulum et, lacinia et leo. Suspendisse potenti. Maecenas eget est augue. Donec tincidunt mollis fermentum.

Contact me?

 
 
 

Donec mi eros, congue ut consectetur eget, pretium vitae orci. Aliquam pharetra ultricies lobortis. Morbi eget nisi lectus. Maecenas felis augue, molestie in vestibulum et, lacinia et leo. Suspendisse potenti. Maecenas eget est augue. Donec tincidunt mollis fermentum.

Send the message
 

Android中解析XML文件并传输数据

         现在我们学习的的网络传输数据交换格式有两种:

         JSON:以键值对的方式存储字符串,这样的字符串可以直接转化为对象。

        XML:可扩展语言(超文本语言),主要用于交换数据。

       在XML中有一个SAX,这个是用于解析的器,他的特点:逐行解析,占用内存少,解析速度也比较快。

所以,我今天带给大家的是利用XML交换数据。JSON比较简单,但是,这两种都是Android网络应用中常用的两种,需要掌握.

    开始,我们会建立一个服务端,用于建立一个自定义的XML文件:

       先建立一个Folder,然后在自定义一个xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<Resource>
<Sing_info>
<Id>001</Id>
<Singer_name>Wanting</Singer_name>
<Sing_Name>Jar of love</Sing_Name>
</Sing_info>
<Sing_info>
<Id>002</Id>
<Singer_name>WestLife</Singer_name>
<Sing_Name>Forever love</Sing_Name>
</Sing_info>
</Resource>

   我们可以先根据地址进行访问以下,是否成功!

  然后,我们要建立一个客户端:

          在客户端里面,我们需要一个实现序列化的接口,用来得到访问服务端的数据后进行赋值。

          我们还需要一个得到post请求书局方式的辅助类,里面主要得到请求方式,然后与得到客户端的值与服务端进行交互,然后返回数据。

        这里还需要一个主要的Activity和一个myHandler类继承DefaultHandler,并且重写里面的三个方法:charactersendElementstartElement

这里我们就先看看辅助类里面的代码:

 

package cn.xml.utils;

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

 

public final class XML_Utils {
/*
* here ,need to create a utils to get the request
*/
public static String sendPost(String baseUrl, String Params) {
// define a url to get the url
URL url;
try {
url = new URL(baseUrl);

 

try {
// to get the request methos is post or get
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
// set the engry
con.setDoInput(true);
con.setDoOutput(true);
// to output the stream
if (null != Params) {
OutputStream op = con.getOutputStream();
PrintWriter pw = new PrintWriter(op);
// to write the params in the pw
pw.print(Params);
pw.flush();

 

}
// to new a inputstreamt to input the stream
InputStream ip = con.getInputStream();
// and to create a bufferreader to get the stream
BufferedReader br = new BufferedReader(
new InputStreamReader(ip));
// to new a string buffered to get the content
StringBuffer sb = new StringBuffer();
// to create a string to get the stream
String str = null;
if ((str = br.readLine()) != null) {
sb.append(str + "\n");

 

}
// to close the stream
br.close();
ip.close();
// to syso
System.out.println(sb);
return sb.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString()+"this is a e";
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
return e.toString()+"this is a e";
}

 

}

 

}

,然后,我们会由辅助类返回一些数据,这时,我们就可以利用我们实体类以及handler,可以用来得到这些值:

实体类:

package cn.xml.entity;

import java.io.Serializable;

public class xml_Entityable implements Serializable{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String Singer_name;
public String getSinger_name() {
return Singer_name;
}
public void setSinger_name(String singer_name) {
Singer_name = singer_name;
}
public String getSing_name() {
return Sing_name;
}
public void setSing_name(String sing_name) {
Sing_name = sing_name;
}
public String Sing_name;
@Override
public String toString() {
return "xml_Entityable [id=" + id + ", Singer_name=" + Singer_name
+ ", Sing_name=" + Sing_name + "]";
}


},再看看继承defaultHandler里面的代码:

package cn.xml.entity;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


/*
* here need to extends the defaulthandler
*
* and there need to implement three methods of the defaultHandler
* */

public class myHandler extends DefaultHandler {

// to new a entity
xml_Entityable entity=new xml_Entityable();
//to define a list to get the allmusic
private ArrayList<xml_Entityable> allMusic=new ArrayList<xml_Entityable>();
// to define a get method
public ArrayList<xml_Entityable> getAllMusic(){
return allMusic;

}
//to define a string that name is Tag
private String Tag="";
//get the characters of the entity
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
//to define a string to get the data
String str=new String(ch,start,length);
if(Tag=="Sing_Name"){
entity.setSing_name(str);

}else if(Tag=="Singer_name"){
entity.setSinger_name(str);

}else if(Tag=="Id"){
entity.setId(str);

}

}
// to do something when the endElement
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(localName=="Sing_info"){
allMusic.add(entity);

}
Tag="";

}
// to do something when the startElement
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
System.out.println(localName+"s--------------df"+qName+"awefq");
Tag=localName;
if(Tag.equals("Sing_info")){
entity=new xml_Entityable();

}
}

},

最后我们就可以看看实现功能的主类:

package cn.xml.client;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import cn.xml.entity.myHandler;
import cn.xml.entity.xml_Entityable;
import cn.xml.utils.XML_Utils;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class XML_Client_11Activity extends Activity {
/**
* 这里我们需要一个接口
* 需要一个实体类(去获得与服务端返回的2数据以及赋值)
* /
/** Called when the activity is first created. */
private ListView disListView;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//to set the values
disListView=(ListView) findViewById(R.id.list);

}
//to define a url
public String baseUrl="http://192.168.1.108:8080/XML_Server_11/Resourse/Main.xml";
//to implement the method of the button
public void onAction(View v){
//to do the button to get the xml's content
//and there need to new a thread
new Thread(new Runnable() {

@Override
public void run() {
//to send the request
String str=XML_Utils.sendPost(baseUrl, null);
System.out.println(str);
//to get the factory
SAXParserFactory factory=SAXParserFactory.newInstance();
//to get the parser(a mechine of the XML)
try {
SAXParser par=factory.newSAXParser();
//to get the stream
XMLReader reader=par.getXMLReader();
//to new a handler
myHandler handler=new myHandler();
//to set the handler to the reader
reader.setContentHandler(handler);
ArrayList<xml_Entityable> musicInfos=handler.getAllMusic();
//to send the msg
Message msg=mHandler.obtainMessage();
msg.obj=musicInfos;
mHandler.sendMessage(msg);

try {
reader.parse(new InputSource(new StringReader(str)));
//and there need to send a ms
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}
}).start();

}
Handler mHandler =new Handler(){

public void handleMessage(Message msg) {

ArrayList<xml_Entityable> allMusic=(ArrayList<xml_Entityable>) msg.obj;



//定义一个集合,用于显示歌曲的名称
ArrayList<String> songs=new ArrayList<String>();

for (xml_Entityable song : allMusic) {

songs.add(song.getSing_name());
System.out.println(songs);
}

ArrayAdapter<String> adapter=new ArrayAdapter<String>(XML_Client_11Activity.this, android.R.layout.simple_list_item_1,android.R.id.text1,songs);

disListView.setAdapter(adapter);
}
};
}

当然,这里我们布局文件里面的代码是不可少的:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="XML" />
<Button
android:id="@+id/btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Dot me to look the XML"
android:onClick="onAction"
/>
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"

/>

</LinearLayout>

记住,这里我们涉及到权限:

<!-- 添加网路权限 -->

<uses-permission android:name="android.permission.INTERNET"/>

 

posted @ 2013-12-23 23:19  Catherine_Brain  阅读(527)  评论(0编辑  收藏  举报