无聊的时候看Android下使用xml的例子不爽了,找到DOM的本地化实现JDOM,发现官网已经声明2.0可以支持Android了,兴高采烈拿来用发现jar编译的有问题不能通过dx编译,难道是我的方法搞错了?好吧,怕了你了,我自己改还不行么?
找到JDOM源码,添加到工程的libs目录(这个目录是自己建立的),并且添加这个目录到源码目录,之后代码拷贝进去后删除一些用来test的类和一些编译错误的类,接着开始使用:
读取:
SAXBuilder builder = new SAXBuilder();
InputStream ins = null;
try {
ins = new FileInputStream("/sdcard/test.xml");
Document doc = null;
doc = builder.build(ins);
Element root = doc.getRootElement();
List<Element> elements = root.getChildren();
for(Element e: elements) {
Log.v(TAG , e.getName());
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (JDOMException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
finally {
try {
ins.close();
} catch (IOException e) {
e.printStackTrace();
}
}
写入的例子:
Document doc = new Document();
Element eRoot = new Element("Persons");
Element ePerson = new Element("Person");
Attribute aPerson = new Attribute("age", "20");
ePerson.setText("文本内容");
ePerson.setAttribute(aPerson);
eRoot.addContent(ePerson);
doc.addContent(eRoot);
XMLOutputter out = new XMLOutputter();
Format format = Format.getPrettyFormat();
out.setFormat(format);
OutputStream writer = null;
try {
writer = new FileOutputStream("/sdcard/test.xml");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
out.output(doc, writer);
} catch (IOException e) {
e.printStackTrace();
}
主要是由于JDOM的代码写起来比较好看,我更喜欢这种清晰的结构。
编译的源代码地址一样上传了,在http://download.youkuaiyun.com/detail/cockroach/4320428,请自行下载。