Java学习之路――使用DOM解析XML文档(一)

2014-11-24 03:07:55 · 作者: · 浏览: 5

第一种方式:使用dom获取属性的值和文本的值进行解析xml

package com.lcq.java.document;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

public class DomTest1 {

/**

* @param args

* @throws Exception

*/

public static void main(String[] args) throws Exception {

//第一步:获得dom解析工厂

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

//第二部:获得dom解析器

DocumentBuilder db = dbf.newDocumentBuilder();

//第三部:解析一个xml文档,获得Document对象(根节点)

Document document = db.parse(new File("test.xml"));

System.out.println(document.getXmlEncoding());

System.out.println(document.getXmlVersion());

System.out.println(document.getXmlStandalone());

NodeList nodeList = document.getElementsByTagName("resourceitem");

System.out.println(nodeList.getLength());

for(int i = 0; i < nodeList.getLength(); i++){

Element element = (Element)nodeList.item(i);

String title = element.getElementsByTagName("title").item(0).getFirstChild().getNodeva lue();

System.out.println("title :" + title);

String keywords = element.getElementsByTagName("keywords").item(0).getFirstChild().getNodeva lue();

System.out.println("keywords :" + keywords);

String kind = element.getElementsByTagName("kind").item(0).getFirstChild().getNodeva lue();

System.out.println("kind :" + kind);

String describe = element.getElementsByTagName("describe").item(0).getFirstChild().getNodeva lue();

System.out.println("describe :" + describe);

String date = element.getElementsByTagName("date").item(0).getFirstChild().getNodeva lue();

System.out.println("date :" + date);

System.out.println("------------------------------------------");

}

}

}

运行结果:

\

第二种方式:运用递归方法解析一般的xml文档

package com.lcq.java.document;

/**

*

* 功能:运用递归方法解析一般的xml文档

*

*/

import java.io.File;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Attr;

import org.w3c.dom.Comment;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.NamedNodeMap;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

public class DomTest3 {

/**

* @param args

* @throws Exception

*/

public static void main(String[] args) throws Exception {

//第一步:获得dom解析工厂

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

//第二部:获得dom解析器

DocumentBuilder db = dbf.newDocumentBuilder();

//第三部:解析一个xml文档,获得Document对象(根节点)

Document document = db.parse(new File("test.xml"));

//获得根元素结点

Element root = document.getDocumentElement();

//调用递归函数,打印xml的内容

parseElement(r