Dom解析xml文件

Dom解析xml的步骤:

  (1)创建一个DocumentBuilderFactory对象(用DocumentBuilderFactory.newInstance()创建

     (2)利用DocumentBuilderFactory对象创建DocumentBuilder对象

      (3)利用DocumentBuilder对象创建Document对象

      (4)解析xml文件


1.Java 代码:

  

package com.jxufe.read;

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

/**
 * 对xml的 读取
 * 
 * @author cd
 *
 */
public class XMLDOMRead {

	public static void main(String[] args) {

		// 创建一个DocumentBuilderFactory对象
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		// 创建DocumentBuilder对象
		DocumentBuilder builder;
		try {
			builder = factory.newDocumentBuilder();
			// 通过DocumentBuilder对象加载book.xml文件,并创建Document对象
			Document document = builder.parse("E:/code/xmlreadAndWriter/person.xml");

			
			NodeList nodeList = document.getElementsByTagName("person");
			// 判断是否存在“book1”这样的节点,有就执行下一步奏。
			treverseNode(nodeList);

		} catch (Exception e) {
			throw new RuntimeException("DOM解析xml文件失败", e);
		}
	}

	private static void treverseNode(NodeList nodeList) {
		if (nodeList == null)
			return;
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i);
			/*
			 * 获取节点为“book1”的属性值
			 */
			NamedNodeMap attributes = node.getAttributes();
			for (int j = 0; j < attributes.getLength(); j++) {
				System.out.println(attributes.item(j).getNodeName() + ":" + attributes.item(j).getNodeValue());
			}
			/**
			 * 获取节点为“book1”的子节点信息
			 */
			NodeList childNodes = node.getChildNodes();
			if (childNodes != null) {
				for (int j = 0; j < childNodes.getLength(); j++) {
					if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE)
						System.out.println(
								// 不能用getNodeValue()方法获取节点的文本,也可以通过getTextcontent获取。
								childNodes.item(j).getNodeName() + ":"
										+ childNodes.item(j).getFirstChild().getNodeValue());
				}
			}
		}
	}
}
2.xml文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<world>
     <person id="1">
         <name>张三</name>
         <gender>女</gender>
         <age>24</age>
     </person>
     <person id="2">
         <name>张三</name>
         <gender>女</gender>
         <age>24</age>
     </person>
</world>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值