자바 분석 xml 의 DOM and SAX
**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/
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.