首先是xml数据格式
<cook>
<name>枸杞肉丝</name>
<type>全部</type>
<feature>滋阴补肾。适于体弱乏力、肾虚目眩、视觉模糊等症。</feature>
<material>枸杞、瘦猪肉青笋调料:精盐、白糖、味精、料酒、酱油、淀粉、猪油、麻油</material>
<production>1、将猪肉洗净去筋,切成2寸长的丝;青笋切成同样的丝;枸杞洗净。2、炒锅上火,将猪油烧热,再将肉丝、笋丝同时下锅炒散,下料酒、白糖、酱油、盐、味精搅匀,投入枸杞,翻炒几下,淋麻油即成。</production>
</cook>
然后我们要新建一个类用来存放我们读取到的数据
package com.example.cookbook.data;
import java.io.Serializable;
public class CBInfo implements Serializable {
private String name;
private String type;
private String feature;
private String material;
private String production;
private String isCollected;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
public String getType()
{
return type;
}
public void setType(String type)
{
this.type=type;
}
public String getFeature()
{
return feature;
}
public void setFeature(String feature)
{
this.feature=feature;
}
public String getMaterial()
{
return material;
}
public void setMaterial(String material)
{
this.material=material;
}
public String getProduction()
{
return production;
}
public void setProduction(String production)
{
this.production=production;
}
public String isCollected()
{
return isCollected;
}
public void setCollected(String isCollected)
{
this.isCollected=isCollected;
}
}
接下来我们要从新建一个类用来读取xml文件
package com.example.cookbook.data;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import com.example.cookbook.R;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.util.Xml;
public class CBInfoRead {
private Context context;
public CBInfoRead (Context context)
{
this.context=context;
}
public List<CBInfo> getAllCooks() throws Throwable
{
AssetManager am=null;
am=context.getAssets();
InputStream ins=am.open("cookbook.xml");
List<CBInfo> cooks=new ArrayList<CBInfo>();
CBInfo info=null;
XmlPullParser parser=Xml.newPullParser();
parser.setInput(ins,"utf-8");
int xmltype=parser.getEventType();
while(xmltype!=XmlPullParser.END_DOCUMENT)
{
switch(xmltype)
{
case XmlPullParser.START_TAG:
String name=parser.getName();
if("cook".equals(name))
{
info=new CBInfo();
}
else if("name".equals(name))
{
info.setName(parser.nextText());
}
else if("type".equals(name))
{
info.setType(parser.nextText());
}
else if("feature".equals(name))
{
info.setFeature(parser.nextText());
}
else if("material".equals(name))
{
info.setMaterial(parser.nextText());
}
else if("production".equals(name))
{
info.setProduction(parser.nextText());
}
break;
case XmlPullParser.END_TAG:
if("cook".equals(parser.getName()))
{
cooks.add(info);
}
break;
default:break;
}
xmltype=parser.next();
}
return cooks;
}
}