Java学习之路——使用DOM解析XML文档
第一种方式:使用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().getNodeValue(); System.out.println("title :" + title); String keywords = element.getElementsByTagName("keywords").item(0).getFirstChild().getNodeValue(); System.out.println("keywords :" + keywords); String kind = element.getElementsByTagName("kind").item(0).getFirstChild().getNodeValue(); System.out.println("kind :" + kind); String describe = element.getElementsByTagName("describe").item(0).getFirstChild().getNodeValue(); System.out.println("describe :" + describe); String date = element.getElementsByTagName("date").item(0).getFirstChild().getNodeValue(); System.out.println("date :" + date); System.out.println("------------------------------------------"); } } }
运行结果:
第二种方式:运用递归方法解析一般的xml文档
运行结果:
转载于:https://www.cnblogs.com/lcqBlogs/archive/2011/10/23/2392380.html