XML解析入门之JDOM(一)

 

package com.liuc.test;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;


import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

public class JdomTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		praseXML(new File("person.xml"));
	}
	
	/**
	 * 解析XML方法
	 */
	public static void praseXML(File xmlFile){
		SAXBuilder sax=new SAXBuilder(); //在内存中建立一个SAX文档模型
		
		try {
			//创建文档
			Document xmlDom=sax.build(xmlFile);
			//获得文档的根元素
			Element root=xmlDom.getRootElement();
			System.out.println("根元素是"+root);
			//获得根元素的子节点
			List childList=root.getChildren();
			Iterator it=childList.iterator();
			while(it.hasNext()){
				Element element=(Element) it.next();
				System.out.println("孩子节点是"+element.getName());
			}
			//获得第一个孩子节点
			Element firstChild=(Element) childList.get(0);
			//获取孩子节点的属性
			List attriList=firstChild.getAttributes();
			Iterator attrIt=attriList.iterator();
			while(attrIt.hasNext()){
				Attribute  attr = (Attribute )attrIt.next();
				System.out.println("第一个元素属性是"+attr.getName());
				System.out.println("属性的值是"+attr.getValue());
				System.out.println("属性的类型是"+attr.getAttributeType());
			}
			
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}//创建文档
	}
}

XML文件
<?xml version="1.0" encoding="UTF-8"?>
<persons>
  <person perid="1001">
    <name>zhangsan</name>
    <age>89</age>
    <address>安徽淮北</address>
    <sex>男</sex>
  </person>
  <person perid="1002">
    <name>lisi</name>
    <age>56</age>
    <address>北京海淀</address>
    <sex>女</sex>
  </person>
</persons>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值