有些时候,我们需要生成一个XML文件,生成XML文件的方法有很多,
如:
可以只使用一个StringBuilder组拼XML内容,然后把内容写入到文件中;
或者使用DOM API生成XML文件,或者也可以使用pull解析器生成XML文件,这里推荐大家使用Pull解析器。
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">lession03_xml</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="btn_sax">采用sax解析xml文件</string> <string name="btn_dom">采用dom解析方式解析</string> <string name="btn_pull">采用pull解析方式解析</string> <string name="btn_cpull">采用pull解析生成xml文件</string> </resources>
<RelativeLayout 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=".XmlActivity" > <Button android:id="@+id/button_cpull" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/btn_pull" android:layout_alignRight="@+id/btn_pull" android:layout_below="@+id/btn_pull" android:layout_marginTop="20dp" android:text="@string/btn_cpull" /> <Button android:id="@+id/btn_sax" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:text="@string/btn_sax" /> <Button android:id="@+id/btn_pull" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/btn_dom" android:layout_alignRight="@+id/btn_dom" android:layout_below="@+id/btn_dom" android:layout_marginTop="68dp" android:text="@string/btn_pull" /> <Button android:id="@+id/btn_dom" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/btn_sax" android:layout_alignRight="@+id/btn_sax" android:layout_below="@+id/btn_sax" android:layout_marginTop="60dp" android:text="@string/btn_dom" /> </RelativeLayout>
package com.example.lession03_xml.domain; import java.io.Serializable; /** * 创建一个javabean存储xml解析的数据 * * @author chenhj * */ public class Person implements Serializable { /** * */ private static final long serialVersionUID = 1L; private int id; private String name; private short age; public Person() { super(); // TODO Auto-generated constructor stub } public Person(int id, String name, short age) { super(); this.id = id; this.name = name; this.age = age; } 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 short getAge() { return age; } public void setAge(short age) { this.age = age; } }
package com.example.lession03_xml.service; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlSerializer; import android.R.bool; import android.os.Environment; import android.provider.ContactsContract.CommonDataKinds.Event; import android.util.Xml; import com.example.lession03_xml.domain.Person; /** * 采用pull解析xml文件 事件驱动 开始,结束元素事件 产生的事件是一个数字,通过switch语句体现 * * @author zhaoyazhi * */ public class XMLPullService { public List<Person> getPerson(InputStream inputStream) throws Exception { List<Person> persons = null; Person person = null; // android提供一个类XmlPullParser,得到pull解析器 XmlPullParser pullParser = Xml.newPullParser(); // 设置要进行解析的内容,不是立刻发生,调用才发生 pullParser.setInput(inputStream, "utf-8"); /* <?xml version="1.0" encoding="UTF-8"?> */ // 触发第一个事件 用数字形式表示 开始文档事件 int event = pullParser.getEventType(); // 不等于文档的结束时间 while (event != XmlPullParser.END_DOCUMENT) { // 属于开始文档事件 switch (event) { case XmlPullParser.START_DOCUMENT: persons = new ArrayList<Person>(); break; case XmlPullParser.START_TAG: /* <persons> */ if ("person".equals(pullParser.getName())) { /* <person id="23"> */ int id = new Integer(pullParser.getAttributeValue(0)); person = new Person(); person.setId(id); } if (person != null) { /* <name> */ if ("name".equals(pullParser.getName())) { // 返回文本的值 /* 李明 */ person.setName(pullParser.nextText()); } /* <age> */ if ("age".equals(pullParser.getName())) { /* 30 */person.setAge(new Short(pullParser.nextText())); } } break; // 结束元素事件 /* </persons> */ case XmlPullParser.END_TAG: // 当前解析器指向的节点为person if ("person".equals(pullParser.getName())) { persons.add(person); person = null; } break; } // 解析器向后解析 event = pullParser.next(); } return persons; } // 写入 public boolean save(List<Person> persons) { // 采用pull解析器进行实现 if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { // 获取SD卡目录 文件对象 File sdCardDir = Environment.getExternalStorageDirectory(); // 创建文件 File file = new File(sdCardDir, "mycsdn.xml"); // xml持久化器 XmlSerializer serializer = Xml.newSerializer(); FileOutputStream fos = null; try { // 根据文件对象创建一个文件的输出流对象 fos = new FileOutputStream(file); // 设置输出流及编码 serializer.setOutput(fos, "UTF-8"); // 设置文件的开始 serializer.startDocument("utf-8", true); // persons标签开始 serializer.startTag(null, "persons"); for (Person person : persons) { // person标签开始 serializer.startTag(null, "person"); // person 属性 serializer.attribute(null, "id", person.getId() + ""); // 设置person标签的子标签name serializer.startTag(null, "name"); serializer.text(person.getName() + ""); serializer.endTag(null, "name"); // 设置person标签子标签age serializer.startTag(null, "age"); serializer.text(person.getAge() + ""); serializer.endTag(null, "age"); // person标签结束 serializer.endTag(null, "person"); } // persons标签的结束 serializer.endTag(null, "persons"); // 文件的结束 serializer.endDocument(); fos.flush(); fos.close(); return true; } catch (Exception e) { e.printStackTrace(); } } return false; } }
package com.example.lession03_xml; import java.io.InputStream; import java.util.List; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import com.example.lession03_xml.domain.Person; import com.example.lession03_xml.service.XMLContentHandlerService; import com.example.lession03_xml.service.XMLDomService; import com.example.lession03_xml.service.XMLPullService; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.Toast; public class XmlActivity extends Activity { // 声明控件 public Button btn_sax, btn_dom, btn_pull, btn_cpull; public XMLDomService xmlDomService; public XMLPullService xmlPullService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 设置显示的视图 setContentView(R.layout.activity_xml); // 实例化 xmlDomService = new XMLDomService(); xmlPullService = new XMLPullService(); // 通过findViewById方法获取控件对象 btn_sax = (Button) findViewById(R.id.btn_sax); btn_dom = (Button) findViewById(R.id.btn_dom); btn_pull = (Button) findViewById(R.id.btn_pull); btn_cpull = (Button) findViewById(R.id.button_cpull); // 给按钮注册事件 btn_sax.setOnClickListener(new MyClickListener()); btn_dom.setOnClickListener(new MyClickListener()); btn_pull.setOnClickListener(new MyClickListener()); btn_cpull.setOnClickListener(new MyClickListener()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.xml, menu); return true; } class MyClickListener implements View.OnClickListener { @Override public void onClick(View v) { // 获取组件的id int id = v.getId(); switch (id) { case R.id.btn_sax: Toast.makeText(XmlActivity.this, "采用sax解析xml文件案例", Toast.LENGTH_LONG).show(); // sax解析的工厂对象 SAXParserFactory factory = SAXParserFactory.newInstance(); try { // 得到sax的解析器 SAXParser saxParser = factory.newSAXParser(); // 创建handler对象 XMLContentHandlerService handlerService = new XMLContentHandlerService(); // 获取到了 asserts目录中 csdn.xml文件 InputStream is = getAssets().open("csdn.xml"); // 直接解析 InputStream的流对象 saxParser.parse(is, handlerService); // 通过 handlerService对象 Toast.makeText(XmlActivity.this, "---" + handlerService.getPersons().size(), Toast.LENGTH_LONG).show(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case R.id.btn_dom: InputStream is = null; try { // 获取读取文件的输入流对象 is = getAssets().open("csdn.xml"); // 采用 List<Person> persons = xmlDomService.parseXML(is); // Toast.makeText(XmlActivity.this, "" + persons.get(0).getName(), Toast.LENGTH_LONG) .show(); } catch (Exception e) { e.printStackTrace(); } break; case R.id.btn_pull: List<Person> persons = null; try { persons = xmlPullService.getPerson(getAssets().open( "csdn.xml")); } catch (Exception e) { e.printStackTrace(); } if (persons != null) { Toast.makeText( XmlActivity.this, "采用pull解析xml文件" + persons.get(0).getName() + "--" + persons.get(1).getName(), Toast.LENGTH_LONG).show(); } break; case R.id.button_cpull: // 重新生成一个xml文件 mycsdn.xml List<Person> persons1 = null; try { persons1 = xmlPullService.getPerson(getAssets().open( "csdn.xml")); // 重新生成一个新xml文件 boolean flag = xmlPullService.save(persons1); if (flag) { Toast.makeText(XmlActivity.this, "采用pull解析生产xml文件成功", Toast.LENGTH_LONG).show(); } else { Toast.makeText(XmlActivity.this, "采用pull解析生产xml文件失败", Toast.LENGTH_LONG).show(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } break; default: break; } } } }