解析xml文件有很多中,在手机上最常用的就是asx方式了,占用资源少
ParserXML类
String xmlStr = "<?xml version='1.0' encoding='UTF-8'?>"+
" <nodes>"+
"<node id='1000' pid='0' code='0'>内容分类</node>"+
"</nodes>";
try{
// 创建SAXParserFactory
SAXParserFactory factory = SAXParserFactory.newInstance();
// 创建XMLReader
XMLReader reader = factory.newSAXParser().getXMLReader();
// 为xmlreader设置容器
reader.setContentHandler(new XMLHandler());
// 解析xml文件
reader.parse( new InputSource( new StringReader(xml)));
}
catch(Exception e){
Log.e("解析xml文件出错", e.getMessage().toString());
}
XMLHandler类
String id,pid,code,node;
String tagname;
/**
* 开始解析xml文件事件处理
*/
@Override
public void startDocument() throws SAXException {
System.out.println("开始处理");
}
/**
* 开始解析xml节点事件处理
*/
@Override
public void startElement(String uri, String localName, String qName,
Attributes att) throws SAXException {
System.out.println("开始解析内容");
tagname = localName;
if(localName == "node"){
for (int i = 0; i < att.getLength(); i++) {
if(att.getLocalName(i) == "id"){
id = att.getValue(i);
}else if(att.getLocalName(i) == "pid"){
pid = att.getValue(i);
}else{
code = att.getValue(i);
}
}
}
}
/**
* 解析xml文件节点内容事件处理
*/
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(tagname == "node"){
node = new String(ch,start,length);
}
}
/**
* 结束解析xml节点事件处理
*/
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(localName == "node")
System.out.println("id =" +id);
System.out.println("pid =" +pid);
System.out.println("code =" +code);
System.out.println("node =" +node);
}
/**
* 结束解析xml文件事件处理
*/
@Override
public void endDocument() throws SAXException {
}
在解析本地xml文件的时候,可能会错这样一个错:
At line 2, column 0: XML or text declaration not at start of entity
这是因为在读取xml文件的时候,每一行都加上了换行符"/n",去掉就可以了