这个操作涉及到3个方面:
首先是xml结构
<?xml version="1.0" encoding="utf-8"?>
<products>
<product>
<id>10</id>
<name>show me the money1</name>
<price>2067.25</price>
</product>
<product>
<id>20</id>
<name>show me the money2</name>
<price>520</price>
</product>
<product>
<id>30</id>
<name>show me the money3</name>
<price>2400</price>
</product>
</products>
接下来是xml转换的product对象类
package com.example.entity;
public class Product {
private int id;
private String name;
private float price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
第3步是defaulthandler类
package com.example.xmlhelper;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.example.entity.Product;
public class XML2Product extends DefaultHandler {
private List<Product> products;
private Product product;
private StringBuffer buffer = new StringBuffer();
public List<Product> getProducts()
{
return products;
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException
{
buffer.append(ch, start, length);
super.characters(ch, start, length);
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException
{
if (localName.equals("product"))
{
products.add(product);
}
else if (localName.equals("id"))
{
product.setId(Integer.parseInt(buffer.toString().trim()));
buffer.setLength(0);
}
else if (localName.equals("name"))
{
product.setName(buffer.toString().trim());
buffer.setLength(0);
}
else if (localName.equals("price"))
{
product.setPrice(Float.parseFloat(buffer.toString().trim()));
buffer.setLength(0);
}
super.endElement(uri, localName, qName);
}
@Override
public void startDocument() throws SAXException
{
products = new ArrayList<Product>();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (localName.equals("product"))
{
product = new Product();
}
super.startElement(uri, localName, qName, attributes);
}
}
最后是activity
先建立一个InputStream叫getNetInputStream
private InputStream getNetInputStream(String urlStr) {
try {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
return is;
} catch (Exception e) {
}
return null;
}
在新建list<product>用于返回xml解析数据
private List<Product> getProductList() {
String rootUrl = "http://172.198.1.50/";
String listUrl = rootUrl + "list.xml";
try {
// 实例化一个SAXParserFactory对象
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlReader = parser.getXMLReader();
// 实例化handler,事件处理器
XML2Product helperHandler = new XML2Product();
// 解析器注册事件
xmlReader.setContentHandler(helperHandler);
// 读取文件流
InputStream stream = getNetInputStream(listUrl); // 读取xml
InputSource is = new InputSource(stream);
// 解析文件
xmlReader.parse(is);
return helperHandler.getProducts();
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
自定义baseadapter
public class productadapter extends BaseAdapter {
private Context context;
private LayoutInflater layoutInflater;
private String inflater = Context.LAYOUT_INFLATER_SERVICE;
private List<imagedata> imagedatalist = new ArrayList<imagedata>();
class imagedata {
public String name;
}
public productadapter(Context context) {
this.context = context;
layoutInflater = (LayoutInflater) context
.getSystemService(inflater);
try {
List<Product> products = getProductList();
for (Product product : products) {
imagedata imagedata1 = new imagedata();
imagedata1.name = product.getName();
imagedatalist.add(imagedata1);
}
} catch (Exception e) {
}
}
public int getCount() {
return imagedatalist.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout linearLayout = (LinearLayout) layoutInflater.inflate(
R.layout.mylist, null);
TextView textview1 = ((TextView) linearLayout
.findViewById(R.id.textView1));
textview1.setText(imagedatalist.get(position).name);
return linearLayout;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* 添加网络权限,安卓4.03必须
*/
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
.penaltyLog().penaltyDeath().build());
/**
* 添加网络权限,安卓4.03必须
*/
ListView listview1 = (ListView) findViewById(R.id.listView1);
productadapter myadapter = new productadapter(this);
listview1.setAdapter(myadapter);
}
两个xml布局文件如下
mylist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
</LinearLayout>