2 u012582435 u012582435 于 2014.03.09 22:21 提问

sax解析xml,Tag的设置

Tag在startElement方法执行后变为book,那在character方法中是如何判断preTag的?

public void startDocument() throws SAXException {

books = new ArrayList();

}

@Override  
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {  
    if("book".equals(qName)){  
        book = new Book();  
        book.setId(Integer.parseInt(attributes.getValue(0)));  
    }  
    preTag = qName;//将正在解析的节点名称赋给preTag  
}  

[size=1em]

@Override

public void characters(char[] ch, int start, int length) throws SAXException {

if(preTag!=null){

String content = new String(ch,start,length);

if("name".equals(preTag)){

book.setName(content);

}else if("price".equals(preTag)){

book.setPrice(Float.parseFloat(content));

}

}

}

Csdn user default icon
上传中...
上传图片
插入图片