关于xml的解析,网上提供了许多的解析方式;sax和pull和dom的各有优缺点;
但常用的还是pull这里我就自己理解的pull来解释;pull是基于事件触发的可以认为是流形式的;姑且认为读到一个tag或一串字符都会停顿;
1,数据结构类:
public class Book {
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;
}
@Override
public String toString() {
return "id:" + id + ", name:" + name + ", price:" + price;
}
}
2,xml解析文件:
public class PullBookParser {
private String TAG = "PullBookParser";
private Context context = null;
public PullBookParser(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
public List<Book> readXml(InputStream is) throws XmlPullParserException,
IOException {
List<Book> books = null;
Book book = null;
XmlResourceParser parser = context.getResources().getXml(R.xml.books);
// XmlPullParser parser = Xml.newPullParser(); //
// 由android.util.Xml创建一个XmlPullParser实例
// parser.setInput(is, "UTF-8"); // 设置输入流 并指明编码方式
int eventType = parser.getEventType();
while (eventType != XmlResourceParser.END_DOCUMENT) {//这里体现了pull的流形式,事件主要为eventtype
switch (eventType) {
case XmlResourceParser.START_DOCUMENT:
books = new ArrayList<Book>();
break;
case XmlResourceParser.START_TAG:
String name = parser.getName();
if (name.equalsIgnoreCase("book")) {
book = new Book();
int id = Integer.parseInt(parser.getAttributeValue(null,
"id"));
book.setId(id);
} else if (null != book) {
if (name.equalsIgnoreCase("name")) {
book.setName(parser.nextText());
} else if (name.equalsIgnoreCase("price")) {
float price = Float.parseFloat(parser.nextText());
book.setPrice(price);
}
}
break;
case XmlPullParser.END_TAG:// 结束元素事件
if (parser.getName().equalsIgnoreCase("book") && book != null) {
books.add(book);
book = null;
}
break;
default:
break;
}
eventType = parser.next();
}
return books;
}
@Override
public String serialize(List<Book> books) throws Exception {
// XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
// XmlSerializer serializer = factory.newSerializer();
Log.i(TAG, "laskdjf:" + books.toString());
XmlSerializer serializer = Xml.newSerializer(); // 由android.util.Xml创建一个XmlSerializer实例
StringWriter writer = new StringWriter();
serializer.setOutput(writer); // 设置输出方向为writer
serializer.startDocument("UTF-8", true);
serializer.startTag("", "books");
for (Book book : books) {//流形式页在这里体现
serializer.startTag("", "book");
serializer.attribute("", "id", book.getId() + "");
serializer.startTag("", "name");
serializer.text(book.getName());
serializer.endTag("", "name");
serializer.startTag("", "price");
serializer.text(book.getPrice() + "");
serializer.endTag("", "price");
serializer.endTag("", "book");
}
serializer.endTag("", "books");
serializer.endDocument();
return writer.toString();
}
public void writeFile(String xml) {
try {
Log.i(TAG, xml);
File file = new File("books.xml");
if (file.exists()) {
file.delete();
}
// FileOutputStream fos = new FileOutputStream(file);
FileOutputStream fos = context.openFileOutput("books.xml", Context.MODE_PRIVATE);
fos.write(xml.getBytes("UTF-8"));
fos.close();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
}
3,调用MainActivity.java中
public class MainActivity extends Activity {
private Button readButton = null;
private Button writeButton = null;
private String TAG = "MainActivity";
PullBookParser parser = null;
List<Book> books = null;
private Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
readButton = (Button) findViewById(R.id.read);
writeButton = (Button) findViewById(R.id.write);
readButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
parser = new PullBookParser(context);
books = parser.readXml(null);
for (Book book : books) {
Log.i(TAG, book.toString());
}
} catch (Exception e) {
// Log.e(TAG, e.getMessage());
e.printStackTrace();
}
}
});
writeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String xml = null;
try {
xml = parser.serialize(books);
parser.writeFile(xml);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 序列化
}
});
}
}
4,主布局文件activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/read"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="读取xml" />
<Button
android:id="@+id/write"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="写入xml" />
<Button
android:id="@+id/update"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="更新xml" />
</LinearLayout>
5,初始xml文件book.xml放在res/xml/book.xml中;
<?xml version="1.0" encoding="utf-8"?>
<books>
<book id="1001">
<name>Thinking In Java</name>
<price>80.00</price>
</book>
<book id="1002">
<name>Core Java</name>
<price>90.00</price>
</book>
<book id="1003">
<name>Hello, Andriod</name>
<price>100.00</price>
</book>
</books>
6,在/data/data/包命/files/books.xml中生成的格式同5;