import com.gc.buyticket.bean.AgreementInfo;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class AgreementParser extends DefaultHandler {
private AgreementInfo agreementInfo;
private StringBuilder content = new StringBuilder();
private List agreementList;
public List parse(InputStream in) throws IOException {
agreementList = new ArrayList<>();
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(in,this);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return agreementList;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if (localName.equals("agreement")){
agreementInfo = new AgreementInfo();
String id = attributes.getValue(0);
agreementInfo.setId(Integer.parseInt(id));
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
if (localName.equals("xuhao")) {
this.agreementInfo.setName(this.content.toString().trim());
} else if (localName.equals("neirong")) {
this.agreementInfo.setPrice(this.content.toString().trim());
} else if (localName.equals("description")) {
this.agreementInfo.setDescription(this.content.toString().trim());
}else if(localName.equals("agreement")){
this.agreementInfo.add(agreementInfo);
}
this.content.setLength(0);
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
this.content.append(ch,start,length);
}
}
我想解析一个xml文件,add一直报红
你的agreementInfo没有add这个方法,你应该是想调用agreementList的add吧。