xml文档:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><person>
<p1>
<name>lqw</name>
<age>20</age>
</p1>
<p2>
<name>pcl</name>
<age>26</age>
</p2>
</person>
sax方式只能进行查询操作,不能增删改
打印出整个文档:
执行parse(File f,DefaultHander dh)方法,第一个参数为文件路径,第二个参数是事件处理器
创建一个类,继承事件处理器的类,重写里面的startElement,characters,endElement方法
代码:
class Default extends DefaultHandler{
boolean flag=false;
int id1=1;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
System.out.println("<"+qName+">");
}
public void characters(char[] ch, int start, int length) throws SAXException {
System.out.println(new String(ch, start, length));
}
public void endElement(String uri, String localName, String qName) throws SAXException {
System.out.println("</"+qName+">");
}
获取第一个name元素:
代码:
package cn.itcast.jasptest;
import java.io.IOException;
import javax.xml.namespace.QName;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class TextSax{
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory saxParserFactory=SAXParserFactory.newInstance();
SAXParser saxParser=saxParserFactory.newSAXParser();
saxParser.parse("src/1.xml", new Default());
}
}
class Default extends DefaultHandler{
boolean flag=false;
int id1=1;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// 当解析到name元素时,把flag设置成true
if("name".equals(qName))
flag=true;
}
public void characters(char[] ch, int start, int length) throws SAXException {
//当flag是true时,表示解析到name元素
if(flag==true&&id1==2)
System.out.println(new String(ch, start, length));
}
public void endElement(String uri, String localName, String qName) throws SAXException {
//把flag设置成false,表示name值结束
if("name".equals(qName)) {
flag=false;
id1++;
}
}
}