input.xml文件存放学生信息
<?xml version="1.0" encoding="UTF-8" standalone="no" ?> - <学生花名册> - <学生 性别="男"> <姓名>吴凤龙</姓名> <年龄>30</年龄> <电话>68888888</电话> </学生> - <学生 性别="男"> <姓名>张井满</姓名> <年龄>32</年龄> <电话>88888888</电话> </学生> </学生花名册>
读取XML的代码:
private ArrayList<SMSUnit> readSMSXMLFile(String path, String filename) { File inFile = new File(path, filename); try { inFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } // 为解析XML作准备,创建DocumentBuilderFactory实例,指定DocumentBuilder DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException pce) { System.err.println(pce); // 出异常时输出异常信息,然后退出,下同 System.exit(1); } Document doc = null; try { doc = db.parse(inFile); } catch (DOMException dom) { System.err.println(dom.getMessage()); System.exit(1); } catch (IOException ioe) { System.err.println(ioe); System.exit(1); } // 下面是解析XML的全过程,比较简单,先取根元素"学生花名册" Element root = doc.getDocumentElement(); // 取"学生"元素列表 NodeList students = root.getElementsByTagName("学生"); for (int i = 0; i < students.getLength(); i++) { // 依次取每个"学生"元素 Element student = (Element) students.item(i); // 创建一个学生的Bean实例 StudentBean studentBean = new StudentBean(); // 取学生的性别属性 studentBean.setSex(student.getAttribute("性别")); // 取"姓名"元素,下面类同 NodeList names = student.getElementsByTagName("姓名"); if (names.getLength() == 1) { Element e = (Element) names.item(0); Text t = (Text) e.getFirstChild(); studentBean.setName(t.getNodeValue()); } NodeList ages = student.getElementsByTagName("年龄"); if (ages.getLength() == 1) { Element e = (Element) ages.item(0); Text t = (Text) e.getFirstChild(); studentBean.setAge(Integer.parseInt(t.getNodeValue())); } NodeList phones = student.getElementsByTagName("电话"); if (phones.getLength() == 1) { Element e = (Element) phones.item(0); Text t = (Text) e.getFirstChild(); studentBean.setPhone(t.getNodeValue()); } student_Vector.add(studentBean); } }
生成XML的代码:
private void writeXMLFile(String outFile) throws Exception { // 为解析XML作准备,创建DocumentBuilderFactory实例,指定DocumentBuilder DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException pce) { System.err.println(pce); System.exit(1); } Document doc = null; doc = db.newDocument(); // 下面是建立XML文档内容的过程,先建立根元素"学生花名册" Element root = doc.createElement("学生花名册"); // 根元素添加上文档 doc.appendChild(root); // 取学生信息的Bean列表 for (int i = 0; i < student_Vector.size(); i++) { // 依次取每个学生的信息 StudentBean studentBean = (StudentBean) student_Vector.get(i); // 建立"学生"元素,添加到根元素 Element student = doc.createElement("学生"); student.setAttribute("性别", studentBean.getSex()); root.appendChild(student); // 建立"姓名"元素,添加到学生下面,下同 Element name = doc.createElement("姓名"); student.appendChild(name); Text tName = doc.createTextNode(studentBean.getName()); name.appendChild(tName); Element age = doc.createElement("年龄"); student.appendChild(age); Text tAge = doc .createTextNode(String.valueOf(studentBean.getAge())); age.appendChild(tAge); Element phone = doc.createElement("电话"); student.appendChild(phone); Text tPhone = doc.createTextNode(studentBean.getPhone()); phone.appendChild(tPhone); } // 把XML文档输出到指定的文件 Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty("indent", "yes"); t.transform(new DOMSource(doc), new StreamResult(new FileOutputStream( outFile))); }
辅助类,用于存储学生信息:
public class StudentBean { private String sex; // 学生性别 private String name; // 学生姓名 private int age; // 学生年龄 private String phone; // 电话号码 public void setSex(String s) { sex = s; } public void setName(String s) { name = s; } public void setAge(int a) { age = a; } public void setPhone(String s) { phone = s; } public String getSex() { return sex; } public String getName() { return name; } public int getAge() { return age; } public String getPhone() { return phone; } }
上面在生成XML文件时有问题:(只要有这面的代码,在android模拟器上就异常,而且连Oncreate()都不运行,在真机上运行无反应)
不知道为什么会这样,希望大侠们指教:
try { javax.xml.transform.Transformer xformer = javax.xml.transform.TransformerFactory .newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.ENCODING, encoding); // Prepare the DOM document for writing javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource( doc); // Prepare the output file StringWriter writer = new StringWriter(); Result result = new StreamResult(writer); // Write the DOM document to the file xformer.transform(source, result); Log.v(TAG, writer.toString()); } catch (javax.xml.transform.TransformerConfigurationException e) { Log.v(TAG, "TransformerConfigurationException"); e.printStackTrace(); } catch (javax.xml.transform.TransformerException e) { Log.v(TAG, "TransformerException"); e.printStackTrace(); }
明白了,从新看了下API
javax.xml.transform这个包是Since:API Level 8也就是说它是android2.2的api,在android 1.5当然不能用。
我从新找了下API,发现org.xmlpull.v1这个包下的XmlSerializer也可以实现以上的需求:Since:API Level 1
贴个XmlSerializer的例子:
package com.hwttnet.wu.testcreatexml; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import org.xmlpull.v1.XmlSerializer; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.util.Xml; import android.widget.TextView; public class testcreatexml extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView tv = (TextView) findViewById(R.id.mytextview); String str = writeXml(); tv.setText(str); Log.v("testcreatexml", str); Write("blog.xml", writeXml()); } private String writeXml() { XmlSerializer serializer = Xml.newSerializer(); StringWriter writer = new StringWriter(); try { serializer.setOutput(writer); // <?xml version="1.0″ encoding="UTF-8″ standalone="yes"?> serializer.startDocument("UTF-8", true); // <blog number="1″> serializer.startTag("", "blog"); serializer.attribute("", "number", String.valueOf(1)); // <message data="2009-09-23″> serializer.startTag("", "message"); serializer.attribute("", "date", "2009-09-23"); // <title>Android XML</title> serializer.startTag("", "title"); serializer.text("Android XML"); serializer.endTag("", "title"); // <url>http://www.moandroid.com/?p=508</url> serializer.startTag("", "url"); serializer.text("http://www.moandroid.com/?p=508"); serializer.endTag("", "url"); // </message> serializer.endTag("", "message"); // </blog> serializer.endTag("", "blog"); serializer.endDocument(); return writer.toString(); } catch (Exception e) { throw new RuntimeException(e); } } public boolean Write(String path, String txt) { try { OutputStream os = openFileOutput(path, MODE_PRIVATE); OutputStreamWriter osw = new OutputStreamWriter(os); osw.write(txt); osw.close(); os.close(); } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } return true; } }