使用DOM解析XML文件是Java程序員必備的知識,適用于小型的文件解析。
DOM最大的特點(diǎn)是整個(gè)文件必須在內(nèi)存中解析和存儲,對于那些需要對文檔不同部分進(jìn)行重復(fù)、隨機(jī)訪問的應(yīng)用程序。
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person no="1">
<name>張三</name>
<age>21</age>
<sex>男</sex>
</person>
<person no="2">
<name>小紅</name>
<age>18</age>
<sex>女</sex>
</person>
<person no="3">
<name>陳剛</name>
<age>25</age>
<sex>男</sex>
</person>
</persons>
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class DomParse
{
public static void main(String[] args)
{
try
{
new DomParse();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public DomParse() throws Exception
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
String path = "bin/person.xml";
Document doc = db.parse(path);
xmlParse(doc);
}
/* XML解析方法 */
public void xmlParse(Document doc)
{
Node root = doc.getDocumentElement(); // 獲得根節(jié)點(diǎn)
NodeList childs = root.getChildNodes();
for (int i = 0; i < childs.getLength(); i++)
{
/* 輸出節(jié)點(diǎn)屬性 */
Node childNode = childs.item(i);
if (childNode.getNodeType() == Node.ELEMENT_NODE)// 判斷是否為元素節(jié)點(diǎn)
System.out.println(childNode.getNodeName()
+ childNode.getAttributes().item(0).getNodeValue());
/* 輸出節(jié)點(diǎn)值 */
for (int j = 0; j < childNode.getChildNodes().getLength(); j++)
{
Node child = childNode.getChildNodes().item(j);
if (child.getNodeType() == Node.ELEMENT_NODE)
System.out.println(child.getNodeName() + "="
+ child.getFirstChild().getNodeValue());
}
}
}
}