此程序其实是在上一版输出部分项目中再新建一个Activity用来读取xml文件:
Activity文件代码如下:
View Code
public class ReadXmlActivity extends Activity { private TextView idInfoText = null; private TextView nameInfoText = null; private Button readXmlBtn = null; // 操作XML文件的准备 private File file = null; private DocumentBuilderFactory docBuilderFactory = null; private DocumentBuilder docBuilder = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 载入为读取xml文件而写的layout布局 super.setContentView(R.layout.xml_reader); idInfoText = (TextView) findViewById(R.id.idInfoText); nameInfoText = (TextView) findViewById(R.id.nameInfoText); readXmlBtn = (Button) findViewById(R.id.readXmlBtn); readXmlBtn.setOnClickListener(new ReadXmlBtnListener()); } private class ReadXmlBtnListener implements OnClickListener { @Override public void onClick(View v) { // 首先调用检测储存环境的方法 if(!ReadXmlActivity.this.CheckEnvironment()) { return; } else { // 生成XML的方法 ReadXMLFile(); } } }
检测储存环境方法代码与输出部分中完全相同,这里不再写出代码了。
读取xml文件的方法:
View Code
/* 读取XML的方法 */ private void ReadXMLFile() { docBuilderFactory = DocumentBuilderFactory.newInstance(); try { docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(file); // 获取所有节点名为person的节点列表 NodeList nodes = doc.getElementsByTagName("person"); for (int i = 0; i < nodes.getLength(); i++) { // 遍历列表,要注意此"e"节点是<person>节点 Element e = (Element) nodes.item(i); // getFirstChild()为获取文本节点 ReadXmlActivity.this.idInfoText.setText(e.getElementsByTagName("id").item(0).getFirstChild().getNodeValue()); ReadXmlActivity.this.nameInfoText.setText(e.getElementsByTagName("name").item(0).getFirstChild().getNodeValue()); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
效果: