使用XMLStream解析xml文件

package com.zf.test;

import java.io.InputStream;
import java.util.Iterator;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

import org.junit.Test;


public class Test01 {

	@Test
	//使用XMLStream 解析xml文件 (基于光标的方式)
	public void test1() throws Exception{
		InputStream is = Test01.class.getClassLoader().getResourceAsStream("build.xml");	//获取xml文件流
		XMLInputFactory xmlFactory  = XMLInputFactory.newInstance();
		XMLStreamReader reader = xmlFactory.createXMLStreamReader(is);
		while(reader.hasNext()){
			int point = reader.next();
			switch(point){
			case XMLStreamReader.START_ELEMENT :{	//开始节点
				String eleName = reader.getName().toString();
				if("property".equals(eleName)){
					int attCount = reader.getAttributeCount() ;
					for (int i = 0; i < attCount; i++) {
						System.out.printf("%s:%s\t" ,
								reader.getAttributeName(i) ,
								reader.getAttributeValue(i));
					}
					System.out.println();
				}
			}
			case XMLStreamReader.END_ELEMENT :{	  //结束节点

			}
			case XMLStreamReader.CHARACTERS :{	//文本节点

			}

			}
		}

	}


	@Test
	//使用XMLStream 解析xml文件 (基于遍历的方式)
	public void test2() throws Exception{
		InputStream is = Test01.class.getClassLoader().getResourceAsStream("build.xml");	//获取xml文件流
		XMLInputFactory xmlFactory  = XMLInputFactory.newInstance();
		XMLEventReader reader = xmlFactory.createXMLEventReader(is);
		while(reader.hasNext()){
			XMLEvent event = reader.nextEvent() ;
			if(event.isStartElement()){	//如果是开始节点
				StartElement startEle = event.asStartElement() ;
				String eleName = startEle.getName().toString() ;	//得到节点名称
				if("property".equals(eleName)){
					Iterator it  = startEle.getAttributes() ;
					while(it.hasNext()){
						Attribute attr = (Attribute) it.next() ;
						System.out.printf("%s:%s\t" ,
								attr.getName(),
								attr.getValue());
					}
					System.out.println();
				}
			}

		}
	}

}

你可能感兴趣的:(使用XMLStream解析xml文件)