package lzh.xml.cn;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/** 待解析文件“Person.xml”内容:
<?xml version="1.0" encoding="UTF-8"?>
<PERSON>
<name>abc</name>
<tel>123</tel>
<age>33</age>
</PERSON>
*/
/**
* xml简易解析
* @author lzh
*
*/
public class XmlTest {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
// step 1: 获得dom解析器工厂(工作的作用是用于创建具体的解析器), 获得工厂实例
DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
// System.out.println("class name: " + dbfactory.getClass().getName());
// 上一个语句的输出结果 class name:
// com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl
// System.out.println(dbfactory);
// 上一个语句的输出结果com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl@15db9742
// step 2:获得具体的dom解析器
DocumentBuilder dbuilder = dbfactory.newDocumentBuilder();
// System.out.println("class name: " + document.getClass().getName());
// 上一个语句的输出结果class name:
// com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl
// System.out.println(document);
// 上一个语句的输出结果com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl@15db9742
// step3: 解析一个xml文档,获得Document对象(根结点)
Document document = dbuilder.parse("Person.xml");
NodeList list = document.getElementsByTagName("PERSON");
for (int i = 0; i < list.getLength(); i++) {
Element element = (Element) list.item(i);
String content = element.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
System.out.println("name:" + content);
content = element.getElementsByTagName("tel").item(0).getFirstChild().getNodeValue();
System.out.println("tel:"+content);
}
}
}
解析XML-DOM-查询
最新推荐文章于 2024-11-01 14:48:20 发布