Your agreementInfo doesn't have the add method; you probably want to call agreementList's add.
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<AgreementInfo> agreementList;
public List<AgreementInfo> 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);
}
}
I want to parse an xml file, and add keeps flashing red
0 Answer
这家伙很懒,什么都没留下...