Java中Dom解析xml文档

xml文档

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
	<book id="1">
		<name>你好</name>
		<author>李四</author>
		<price>80</price>
	</book>
	<book id="2">
		<name>你好2</name>
		<author>李四2</author>
		<price>81</price>
	</book>
</bookstore>

java文件

package cn.lonecloud.xml;

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.Node;
import org.w3c.dom.NodeList;

public class DomXML {

	public static void main(String[] args) throws Exception {
		//先建立一个DocumentBuilderFactory对象
		DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
		//建立一个buildfactory对象
		DocumentBuilder db=dbf.newDocumentBuilder();
		//获取xml文件
		Document document=db.parse("demo.xml");
		//获取root树的Element
		Element e1=document.getDocumentElement();
		//获取子元素的子节点
		if (e1!=null) {
			NodeList list=e1.getChildNodes();
			if (list!=null) {
				//遍历书子节点
				for (int i = 0; i < list.getLength(); i++) {
					Node node=list.item(i);
					if (node!=null) {
						NodeList child=node.getChildNodes();
						for (int j = 0; j < child.getLength(); j++) {
							Node n=child.item(j);
							//获取属性名称文本
							if (n.getNodeType()==Node.ELEMENT_NODE) {
								//获取节点名称
								System.out.println(n.getNodeName());
								//获取这个节点值
								System.out.println(n.getFirstChild().getNodeValue());
								//获取节点的的值下的所有文本
								System.out.println(n.getTextContent());								
							}
						}
					}
				}
			}
		}
	}

}

  

原文地址:https://www.cnblogs.com/lonecloud/p/5561686.html