1. Briefly describe the characteristics of Dom parsing XML
Each component in the XML document is a node, and its node types are mainly divided into three types:
- element node: each XML tag;
- attribute node: every attribute of every XML tag;
- Text Node: The text of each XML tag.
For more information on node types, see XML DOM Node Types
Dom parsing an XML document is to read the entire document into memory at one time, and build a document document tree object in the memory. Through the API provided by DOM, each node of the document tree object can be operated.
2. Give an example
Parse the following persons.xml
<?xml version="1.0" encoding="utf-8" ?>
<persons>
<person id="p1">
<name>小明</name>
<age>18</age>
</person>
<person id="p2">
<name>小华</name>
<age>23</age>
</person>
</persons>
DOM parsing xml logic class
import org.w3c.dom.Node
import java.io.InputStream
import java.util.ArrayList
import java.util.HashMap
import javax.xml.parsers.DocumentBuilderFactory
/**
* dom解析
* Created by Administrator on 2018/5/7.
*/
class DomXmlParser{
companion object {
fun parseXmlForList(inputStream: InputStream):ArrayList<HashMap<String,String>>{
var mapList = ArrayList<HashMap<String,String>>()
//文档生成器工程
var builderFactory = DocumentBuilderFactory.newInstance()
//文档生成器
var builder = builderFactory.newDocumentBuilder()
//文档
var document = builder.parse(inputStream)
//文档跟节点
var rootElementNode = document.documentElement
rootElementNode.normalize()
//遍历文档子子节点
var i= 0
var elementNode: Node
while (i<rootElementNode.childNodes.length){
//跟节点的子节点
elementNode = rootElementNode.childNodes.item(i)
//过滤空文本节点
if(elementNode.nodeType == Node.ELEMENT_NODE) {
var map = HashMap<String, String>()
var attsNodes = elementNode.attributes
var j = 0
while (j < attsNodes.length) {
var attsTag = attsNodes.item(j).nodeName
(map as HashMap<String, String>).put(attsNodes.item(j).nodeName, attsNodes.item(j).textContent)
j++
}
var sonElementNodes = elementNode.childNodes
//遍历子元素节点
var x =0
while (x<sonElementNodes.length){
var sonElementNode = sonElementNodes.item(x)
//过滤空文本节点
if(sonElementNode!=null && sonElementNode.nodeType == Node.ELEMENT_NODE){
(map as HashMap<String, String>).put(sonElementNode.nodeName,sonElementNode.firstChild.nodeValue)
}
x++
}
mapList.add(map as HashMap<String, String>)
}
i++
}
return mapList
}
}
}
call test
var inputStream = this.assets.open("persons.xml")
var mapList = DomXmlParser.parseXmlForList(inputStream)
if(mapList!=null && mapList.size>0) {
var sb = StringBuffer()
for (map in mapList) {
sb.append("${map.get("id")},${map.get("name")},${map.get("age")}\n")
}
tvDomParse = findViewById(R.id.tv_dom_parse_xml_result)
tvDomParse.text = sb.toString()
}
[ Complete demo ]
References: