public class MainActivity extends Activity implements OnClickListener{
private Button jx;
private String name;
private Books b;
List<Books> list=
new ArrayList<Books>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jx=(Button)findViewById(R.id.jx);
jx.setOnClickListener(
this);
}
@Override
public void onClick(View v) {
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(getAssets().open(
"books.xml"),
"utf-8");
int type = parser.getEventType();
while(type!=XmlPullParser.END_DOCUMENT){
switch (type) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
name = parser.getName();
if (
"book".equals(name)) {
b =
new Books();
String id=parser.getAttributeValue(
0);
b.setId(Integer.parseInt(id));
}
break;
case XmlPullParser.TEXT:
if (name!=
null) {
if (
"name".equals(name)) {
b.setName(parser.getText());
}
else if(
"author".equals(name)){
b.setAuthor(parser.getText());
}
else if(
"price".equals(name)){
b.setPrice(Integer.parseInt(parser.getText()));
}
}
break;
case XmlPullParser.END_TAG:
if(
"book".equals(parser.getName())){
list.add(b);
b=
null;
}
name=
null;
break;
default:
break;
}
type=parser.next();
}
System.out.println(list);
}
catch (XmlPullParserException e) {
e.printStackTrace();
}
catch (IOException e) {
System.out.println(
"文件未找到");
e.printStackTrace();
}
}
}
javabean
public class Books {
private int id;
private String name;
private String author;
private int price;
public Books(
int id, String name, String author,
int price) {
super();
this.id = id;
this.name = name;
this.author = author;
this.price = 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 String
getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getPrice() {
return price;
}
public void setPrice(
int price) {
this.price = price;
}
public Books() {
super();
}
@Override
public String
toString() {
return "Books [id=" + id +
", name=" + name +
", author=" + author
+
", price=" + price +
"]";
}
}
转载请注明原文地址: https://ju.6miu.com/read-1125725.html