자바 분석 xml 의 DOM and SAX

자바 분석 XML 은 두 가지 방법 이 있 습 니 다.
**DOM
**SAX
예:
<?xml version="1.0" encoding="UTF-8"?>
<users>
	<description>information of users</description>
	<user>
		<name>LiLei</name>
		<sex>1</sex>
		<age>19</age>
	</user>
	
	<user>
		<name>Han Meimei</name>
		<sex>0</sex>
		<age>18</age>
	</user>
</users>

DOM 방식:
XML 을 불 러 오고 메모리 에 xml 파일 에 대응 하 는 DOM 트 리 를 만 듭 니 다.
DOM 트 리 의 Node 와 NodeList 에 따라 필요 한 정 보 를 얻 습 니 다.
public boolean parserXml(InputStream is) throws Exception {
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	DocumentBuilder builder = factory.newDocumentBuilder();
	Document doc = builder.parse(is);

	NodeList descNodes = doc.getElementsByTagName("description");
	NodeList userNodes = doc.getElementsByTagName("user");
	if (descNodes.getLength() > 0) {
		// ignore following descriptions
		document.setDescription(descNodes.item(0).getFirstChild().getNodeValue());
	}
	Node node;
	NodeList nodes;
	String name;
	User user;
	for (int i = 0; i < userNodes.getLength(); i++) {
		user = new User();
		nodes = userNodes.item(i).getChildNodes();
		for (int j = 0; j < nodes.getLength(); j++) {
			node = nodes.item(j);
			name = node.getNodeName();
			if ("name".equals(name)) {
				user.setName(node.getFirstChild().getNodeValue());
			} else if ("sex".equals(name)) {
				user.setSex(Integer.parseInt(node.getFirstChild().getNodeValue()));
			} else if ("age".equals(name)) {
				user.setAge(Integer.parseInt(node.getFirstChild().getNodeValue()));
			}
		}
		document.addUser(user);
	}
	return true;
}

** getChildNodes () 에는 공백 과 줄 바 꿈 이 포함 되 어 있 기 때문에 nodes. getLength () 반환 값 은 7 이 고 3 개의 키 노드 를 제외 하고 4 개의 줄 바 꿈 + tab 이 있 습 니 다.그래서 첫 번 째 childNode 는\t\t 입 니 다.
* * name 노드 의 하위 노드 는 1 개, 즉 LiLei 라 는\# text 노드 입 니 다.
SAX 방식:
이벤트 구동 방식.
xml 파일 흐름 을 읽 고 읽 은 노드 에 따라 해당 하 는 이 벤트 를 실행 합 니 다.startDocument (), endDocument (), startElement (), endElement (), characters ()...
/**
 * event driven parse xml as an input stream, with a handler as a callback while
 * meeting each element tag startElement will contain lots of if/else
 * 
 * @author xuefeng
 * 
 */
public class SaxXmlDemo implements IXmlDocument {

	private UserDocument document;

	public SaxXmlDemo() {
		document = new UserDocument();
	}

	public boolean parserXml(InputStream is) throws Exception {
		SAXParserFactory saxfac = SAXParserFactory.newInstance();
		SAXParser saxparser = saxfac.newSAXParser();
		saxparser.parse(is, new MySAXHandler(document));

		return true;
	}

	public static void main(String[] args) throws Exception {
		SaxXmlDemo demo = new SaxXmlDemo();
		FileInputStream fis = new FileInputStream("data/test.xml");
		demo.parserXml(fis);
		System.out.println();
	}
}

class MySAXHandler extends DefaultHandler {

	private UserDocument document;

	private User user; // userd for startElement and endElement

	private String curTag; // userd for startElement and endElement

	public MySAXHandler(UserDocument document) {
		this.document = document;
	}

	public void startDocument() throws SAXException {
	}

	public void endDocument() throws SAXException {
	}

	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		curTag = qName;
		if ("user".equals(qName)) {
			user = new User();
			document.addUser(user);
		}
	}

	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		curTag = null;
	}

	public void characters(char[] ch, int start, int length)
			throws SAXException {
		if (curTag == null)
			return;
		String value = new String(ch, start, length);
		if ("description".equals(curTag)) {
			document.setDescription(value);
		} else if ("name".equals(curTag)) {
			user.setName(value);
		} else if ("sex".equals(curTag)) {
			user.setSex(Integer.parseInt(value));
		} else if ("age".equals(curTag)) {
			user.setAge(Integer.parseInt(value));
		}
	}

}

그 중
public void startElement(String uri, String localName, String qName, Attributes attributes)

uri: 해상도 기 가 네 임 스페이스 를 지원 하면 uri 는 네 임 스페이스 입 니 다.지원 하지 않 거나 네 임 스페이스 가 없 으 면 uri = "
localName : 해상도 기 가 네 임 스페이스 를 지원 한다 면 tag 의 이름 입 니 다.그렇지 않 으 면 비어 있다.
qName: tag 에 네 임 스페이스 접두사 가 있 으 면 접두사 + tag 이름 입 니 다.그렇지 않 으 면 tag 이름 입 니 다.
attributes: tag 의 속성 목록 은 getLength (), getValue () 를 통 해 접근 할 수 있 습 니 다.
본문 코드: svn :  http://hsuehfeng.googlecode.com/svn/trunk/xml/XMLParse/

좋은 웹페이지 즐겨찾기