Android数据存储之DOM解析XML文件(输出部分)
此程序涉及到存储卡的操作,此类操作需要在配置文件中添加写权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
主Activity组件与监听事件准备:
View Code
public class MainActivity extends Activity { private EditText idText = null; private EditText nameText = null; private Button saveXMLBtn = null; // 操作XML文件的准备 private File file = null; private DocumentBuilderFactory docBuilderFactory = null; private DocumentBuilder docBuilder = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); idText = (EditText) findViewById(R.id.idText); nameText = (EditText) findViewById(R.id.nameText); saveXMLBtn = (Button) findViewById(R.id.saveXMLBtn); saveXMLBtn.setOnClickListener(new SaveXMLBtnListener()); } private class SaveXMLBtnListener implements OnClickListener { @Override public void onClick(View v) { // 首先调用检测储存环境的方法 if(!MainActivity.this.CheckEnvironment()) { return; } else { // 生成XML的方法 GenerateXMLFile(); } } }
检测储存环境的方法:
View Code
/* 检测储存环境是否配置正常,并设置文件存放路径 */ private boolean CheckEnvironment() { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { file = new File(Environment.getExternalStorageDirectory().toString() + File.separator + "documents" + File.separator + "shuai.xml"); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } return true; } else { return false; } }
生成XML的方法:
View Code
/* 生成XML的方法 */ private void GenerateXMLFile() { // 实例化文档生成工厂类 docBuilderFactory = DocumentBuilderFactory.newInstance(); try { // 由工厂实例化文档生成类 docBuilder = docBuilderFactory.newDocumentBuilder(); // 实例化一个文档 Document doc = docBuilder.newDocument(); // 设置文档中的所有节点 Element moka = doc.createElement("moka"); Element person = doc.createElement("person"); Element name = doc.createElement("name"); Element id = doc.createElement("id"); // 设置所有节点的子节点(文本节点为叶子节点,无子节点) doc.appendChild(moka); moka.appendChild(person); person.appendChild(name); person.appendChild(id); name.appendChild(doc.createTextNode(MainActivity.this.nameText.getText().toString())); id.appendChild(doc.createTextNode(MainActivity.this.idText.getText().toString())); // 实例化转换器工厂类, 由工厂生成一个转换器类实例,并设置输出参数 TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "GBK"); // 转换器类将xml源文件向一个目的路径保存转换后的结果,这里是一个xml文件 DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(file); transformer.transform(source, result); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } }
操作完毕后会在指定目录下生成文件: