解析 xml

一 、DOM方式

1 、xml文件

<?xml version="1.0" encoding="UTF-8"?>

<players>
	<player id="1">
	  <name>kobe</name>
	  <height>2.01m</height>
	  <nickname>黑曼巴</nickname>
	</player>
	<player id="2">
	  <name>wade</name>
	  <height>1.93m</height>
	  <nickname>闪电侠</nickname>
	</player>
</players>

2 、解析代码

package com.souche.sts.demo;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 功能:dom xml解析
 * @author sxl
 *
 */
class Client {
	
	public static void main(String args[]) {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document d = db.parse(new File("E:\\player.xml"));
			NodeList nodeList = d.getElementsByTagName("player");
			System.out.println("共" + nodeList.getLength() + "个球员");
			for (int i = 0; i < nodeList.getLength(); i++) {
				Node node = nodeList.item(i);
				NamedNodeMap attributes = node.getAttributes();
				for (int j = 0; j < attributes.getLength(); j++) {
					Node item = attributes.item(j);
					System.out.println("属性名:" + item.getNodeName() + "===属性值:" + item.getNodeValue());
				}
				NodeList childNodes = node.getChildNodes();
				for (int k = 0; k < childNodes.getLength(); k++) {
					if (childNodes.item(k).getNodeType() == Node.ELEMENT_NODE) {
						Node childNode = childNodes.item(k);
						System.out.println(childNode.getNodeName() + ":" + childNode.getFirstChild().getNodeValue());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

3 、结果

共2个球员
属性名:id===属性值:1
name:kobe
height:2.01m
nickname:黑曼巴
属性名:id===属性值:2
name:wade
height:1.93m
nickname:闪电侠

二 、DOM4J方式

	public static void dom4j () {
		SAXReader reader = new SAXReader();
		try {
			org.dom4j.Document read = reader.read(new File("E:\\player.xml"));
			Element rootElement = read.getRootElement();
			Iterator elementIterator = rootElement.elementIterator();
			while (elementIterator.hasNext()) {
				Element next = (Element)elementIterator.next();
				List<Attribute> attributes = next.attributes();
				for (Attribute e : attributes) {
					System.out.println(e.getName() + ":" + e.getStringValue());
				}
				Iterator elementIterator2 = next.elementIterator();
				while (elementIterator2.hasNext()) {
					Element next2 = (Element)elementIterator2.next();
					System.out.println(next2.getName() + ":" + next2.getStringValue());
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值