下面是具体的“Android创建与解析XML(二)——详解Dom方式”攻略。
1. 什么是Dom
Dom,全称为 Document Object Model,是一种基于树形结构的API,用于表示和操作xml文档。
2. Dom的使用
(1)导入相应的类库
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
(2)创建DocumentBuilderFactory对象和DocumentBuilder对象
try {
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
} catch (Exception e) {
e.printStackTrace();
}
(3)使用DocumentBuilder对象解析xml文档,返回Document对象
try {
File file = new File("book.xml");
Document document = builder.parse(file);
} catch (Exception e) {
e.printStackTrace();
}
(4)获取xml文档中的Element
Element rootElement = document.getDocumentElement();
(5)获取xml文档中的NodeList
NodeList nodeList = rootElement.getElementsByTagName("book");
(6)遍历NodeList,获取每个Node,进行操作
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String id = element.getAttribute("id");
String name = element.getElementsByTagName("name")
.item(0).getTextContent();
String author = element.getElementsByTagName("author")
.item(0).getTextContent();
String price = element.getElementsByTagName("price")
.item(0).getTextContent();
System.out.println(id + "\t" + name + "\t" + author + "\t" + price);
}
}
3. 示例说明
(1)创建xml文档
<?xml version="1.0" encoding="utf-8"?>
<books>
<book id="001">
<name>Java程序设计</name>
<author>张三</author>
<price>69.9</price>
</book>
<book id="002">
<name>IOS开发入门</name>
<author>李四</author>
<price>89.5</price>
</book>
</books>
(2)解析xml文档
try {
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
File file = new File("book.xml");
Document document = builder.parse(file);
Element rootElement = document.getDocumentElement();
NodeList nodeList = rootElement.getElementsByTagName("book");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String id = element.getAttribute("id");
String name = element.getElementsByTagName("name")
.item(0).getTextContent();
String author = element.getElementsByTagName("author")
.item(0).getTextContent();
String price = element.getElementsByTagName("price")
.item(0).getTextContent();
System.out.println(id + "\t" + name + "\t" + author + "\t" + price);
}
}
} catch (Exception e) {
e.printStackTrace();
}
输出结果:
001 JAVA程序设计 张三 69.9
002 IOS开发入门 李四 89.5
以上就是“Android创建与解析XML(二)——详解Dom方式”的完整攻略,希望能对您有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Android创建与解析XML(二)——详解Dom方式 - Python技术站