Java语言解析Xml文件有多种方式,本文章采用dom解析
解析出来的dom对象,其常用方法的使用例子网上比比皆是,但解析出来的dom对象的结构是怎样的呢?
首先得先了解下Dom对象的节点类型
下面使用例子讲解
XML文件:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<department>我是department
<student id="110">我是lili
<name>lili</name>
<age>100</age>
</student>
<student id="220">我是mary
<name>Mary</name>
<age>20</age>
</student>
<student id="330">我是Terry
<name>Terry</name>
<age>20</age>
</student>
</department>
Java代码:
public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
//创建工厂
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
//创建DocumentBuilder 实例
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
//加载配置文件流,获取其Document对象,此处虽然使用ClassPathResource,但其本质上还是使用的类加载器加载文件流
Document doc = documentBuilder.parse(new ClassPathResource("dom.xml").getInputStream());
Element root = doc.getDocumentElement();
//获取其第一级子节点
NodeList childs = root