package hello;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import java.util.ArrayList;
import java.util.List;
public class XML_SAXReader {
public static void main(String[] args) {
try {
XMLReader parser = XMLReaderFactory.createXMLReader();
UserHandler userHandler = new UserHandler();
parser.setContentHandler(userHandler);
parser.parse("users.xml");
System.out.println(userHandler.getNameList());
} catch (Exception e) {
e.printStackTrace();
}
}
static class UserHandler extends DefaultHandler {
private List<String> nameList;
private boolean isName = false;
public List<String> getNameList() {
return nameList;
}
public void startDocument() throws SAXException {
System.out.println("开始解析文档...");
this.nameList = new ArrayList<String>();
}
// xml 文档解析结束
public void endDocument() throws SAXException {
System.out.println("...文档解析完毕");
}
// 访问某一个元素
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
System.out.println("开始读取标签 " + qName);
if (qName.equals("name")) {
isName = true;
}
}
// 结束访问元素
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
System.out.println("结束读取标签 " + qName);
if (isName) {
isName = false;
}
}
// 访问元素正文
public void characters(char[] ch, int start, int length) {
if (isName) {
String name = new String(ch, start, length);
System.out.println("userName: " + name);
nameList.add(name);
}
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user id="001">
<name>Mary</name>
<age>3</age>
<sex>Female</sex>
</user>
<user id="002">
<name>Mike</name>
<age>18</age>
<sex>Male</sex>
</user>
<user id="003">
<name>ZhaZhaHui</name>
<age>38</age>
<sex>Male</sex>
</user>
</users>
原文地址:https://www.cnblogs.com/sweetXiaoma/p/12653588.html
时间: 2024-10-16 08:02:56