Xml基础

package com.chai.xml;

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

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XPPReader;

public class Xml {
	public static void main(String[] args) {
		SAXReader reader=new SAXReader();
		try {
			Document doc=reader.read(new File("src/com/chai/xml/stu.xml"));
			//获取 根目录
			Element root=doc.getRootElement();
			//获取 根目录遍历器
			Iterator it=root.elementIterator();
			//进行遍历
			while(it.hasNext()){
				//强转成 元素 Element
				Element element=(Element)it.next();
				//输出根元素名称
				System.out.println("-----"+element.getName());
				//输出根元素属性
				System.out.println("-"+element.attributeValue("id"));
				//获取 name 元素
				Element element1=element.element("name");
				//输出 name元素内容
				System.out.println("--"+element1.getText());
				//获取 password 元素
				Element element2=element.element("password");
				//输出password 元素内容
				System.out.println("--"+element2.getText());
				//hobbys元素 下游子元素 所以先
				Iterator its=element.elementIterator("hobbys");
				while(its.hasNext()){
					Element el=(Element)its.next();
					Element element4=el.element("hobby1");
					System.out.println("---"+element4.getText());
					Element element5=el.element("hobby2");
					System.out.println("---"+element5.getText());
				}
			}
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 

<?xml version="1.0" encoding="UTF-8"?>
<stu>
	<student id="1001">
		<name>Tom</name>
		<password>123</password>
		<hobbys>
			<hobby1>eating</hobby1>
			<hobby2>beating</hobby2>
		</hobbys>
	</student>
	
	
	<student id="1002">
		<name>Cat</name>
		<password>321</password>
		<hobbys>
			<hobby1>eating2</hobby1>
			<hobby2>beating2</hobby2>
		</hobbys>
	</student>
</stu>

 

你可能感兴趣的:(xml)