DOM解析XML案例Demo(一)

一、Java中操作DOM中常用的类

  • Node 
    数据类型基类
  • Element 
    最常用的类
  • Attr 
    Element的属性
  • Text 
    Element or Attr的内容
  • Document 
    代表整个XML文档,代表DOM tree

二、xml文件

<?xml version = "1.0" encoding = "utf-8"?>
<books>
	<book id="1">
		<name>冰与火之歌</name>
		<author>张三</author>
		<pice>99</pice>
	</book>
	<book id="2">
		<name>葫芦娃</name>
		<pice>99</pice>
		<year>1993</year>
	</book>
</books>

三、Dom解析XML案例Demo

package com.da.dom;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DomTest {

	public static void main(String[] args) {
		//创建一个DocumentBuilderFactory对象
		DocumentBuilderFactory documentBuilder = DocumentBuilderFactory.newInstance();
		try {
			//创建DocumentBuilder对象
			DocumentBuilder db = documentBuilder.newDocumentBuilder();
			//通过DocumentBuilder中的parse方法加载book。xml文件到当前项目下
			Document document = db.parse("books.xml");
			//获取所有book节点的集合
			NodeList nodeList = document.getElementsByTagName("book");
			//遍历每个book节点
			for (int i = 0; i < nodeList.getLength(); i++) {
				System.out.println("==========第"+(i+1)+"本==========");
//				Node book = nodeList.item(i);
//				NamedNodeMap attributes = book.getAttributes();
//				//不知道当前节点下有多少参数属性值
//				for (int j = 0; j < attributes.getLength(); j++) {
//					Node item = attributes.item(j);
//					System.out.print("获取属性名:"+item.getNodeName());
//					System.out.println("获取属性值:"+item.getNodeValue());
//				}
				//确切当前参数下有多少参数属性值
				Element element = (Element) nodeList.item(i);
				System.out.println("id值:"+element.getAttribute("id"));
				//获取book下面的子节点
				NodeList childNodes = nodeList.item(i).getChildNodes();
				for (int j = 0; j < childNodes.getLength(); j++) {
					if (childNodes.item(j).getNodeType() == Node.ELEMENT_NODE) {
						System.out.print(childNodes.item(j).getNodeName()+":");
						System.out.println(childNodes.item(j).getTextContent());
					};
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

转载于:https://my.oschina.net/Clarences/blog/1788748

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值