sax解析xml文件问题
package com.java.xml;
import java.io.File;
import java.util.ArrayList;
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 MyHandler extends DefaultHandler{
ArrayList<Person>students=null;
StringBuilder builder=null;
Person student=null;
public MyHandler(ArrayList<Person> students){
this.students=students;
}
public void startDocument()throws SAXException{
super.startDocument();
//students=new ArrayList<Person>();
builder=new StringBuilder();
}
public void startElement(String uri,String localName,String qName,Attributes attributes)throws SAXException{
super.startElement(uri, localName, qName, attributes);
if(localName.equals("student")){
student=new Person();
student.id=new Integer(attributes.getValue("id"));
}
builder.setLength(0);
if(uri==null){System.out.println("uri is null");}
System.out.println(uri);
System.out.println(localName);
System.out.println("s");
}
public void characters(char[]ch,int start,int length)throws SAXException{
super.characters(ch, start, length);
builder.append(ch,start,length);
}
public void endElement(String uri,String localName,String qName)throws SAXException{
super.endElement(uri, localName, qName);
if(localName.equalsIgnoreCase("name")){
student.name=builder.toString();
}else if(localName.equalsIgnoreCase("age")){
student.age=new Integer(builder.toString());
}else if(localName.equals("student")){
students.add(student);
}
}
public void endDocument()throws SAXException{
super.endDocument();
}
public static void main(String[]args){
ArrayList<Person> students=new ArrayList<Person>();
try{
SAXParserFactory factory=SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
MyHandler handler=new MyHandler(students);
File f=new File("a.xml");
parser.parse(f, handler);
System.out.println(students.size()+"----end");
}catch(Exception e){
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" title="XSL Formatting" href="/show_new_final.xsl" media="all"?>
<students>
<student id="1">
<name>tyy1</name>
<age>21</age>
</student>
<student id="2">
<name>tyy2</name>
<age>22</age>
</student>
<student id="3">
<name>tyy3</name>
<age>23</age>
</student>
<student id="4">
<name>tyy4</name>
<age>24</age>
</student>
</students>
为什么输入结果一直为空? --------------------编程问答-------------------- 你的file路径不全,肯定为空啊,写成绝对路径c:\\new.file,或者相对路径都可以 --------------------编程问答-------------------- 在文件下边加上
if(f.exists()){
//如果存在就不是一楼说的问题
} --------------------编程问答-------------------- 代码太长,哈哈
补充:Java , Java相关