最近在学习XML、并且用Java对它进行各种操作、哎呀妈啊、不仅累、有时候还被自己给转懵圈了。
解析分为两种:
DOM解析:全载入到内存、耗内存大
SAX解析:基于事件、瞬时读、消耗特小。如果再解析,重读 默认基类:DefaultHandler
目前应该用DOM比较多吧。SAX没有深入的了解
一、DOM解析
1、基础----对下面XML进行解析
<?xml version="1.0" encoding="UTF-8"?>
<products>
<product id="p001">
<name>MP3</name>
<price>200</price>
</product>
<product id="p002">
<name>MP4</name>
<price>220</price>
</product>
</products>
public static void main(String[] args) {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
String path = DOMTest.class.getResource("Phone.xml").getPath()
.substring(1);
try {
DocumentBuilder documentBuilder = documentBuilderFactory
.newDocumentBuilder();
Document document = documentBuilder.parse(path);
NodeList list = document.getElementsByTagName("product");
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
System.out.println(node.getNodeName());
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element e = (Element) node;
String id = e.getAttribute("id");
System.out.println("id:" + id);
NodeList cn = e.getChildNodes();
for (int j = 0; j < cn.getLength(); j++) {
Node childNode = cn.item(j);
if (childNode.getNodeType() == Node.ELEMENT_NODE) {
Element childEle = (Element) childNode;
System.out.println(childEle.getNodeName()
+ childEle.getTextContent());
}
}
}
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}