我正在使用 SAX 解析 XML。我在我见过的 tje 互联网示例上编写了代码。我得到了 url,然后我解析了这个。这是我的代码。
public class Urunler implements Serializable {
private String title;
private String description;
public Urunler(String title, String description) {
this.title = title;
this.description = description;
}
public Urunler() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String cevir() {
StringBuffer sb = new StringBuffer();
sb.append("Title:" + getTitle());
sb.append(", ");
sb.append("Description:" + getDescription());
sb.append(".");
return sb.toString();
}
}
然后我写了一个解析处理程序。它在下面;
public class UrunlerHandler extends DefaultHandler{
private Urunler urunler;
private String temp;
private ArrayList<Urunler> urunlerList= new ArrayList<Urunler>();
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
temp = "";
if(qName.equalsIgnoreCase("item")){
urunler = new Urunler();
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
temp = new String(ch,start,length);
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equalsIgnoreCase("item")){
urunlerList.add(urunler);
}else if(qName.equalsIgnoreCase("title")){
urunler.setTitle(temp);
}else if(qName.equalsIgnoreCase("description")) {
urunler.setDescription(temp);
}
}
public void readList(){
Iterator<Urunler> it = urunlerList.iterator();
while (it.hasNext()) {
System.out.println(it.next().cevir());
}
}
然后我在这样的 Main 方法中使用过;
try {
SAXParserFactory spfac = SAXParserFactory.newInstance();
SAXParser sp = spfac.newSAXParser();
UrunlerHandler handler = new UrunlerHandler();
URL geoLocationDetailXMLURL = new URL(url);
URLConnection geoLocationDetailXMLURLConnection = geoLocationDetailXMLURL.openConnection();
BufferedReader geoLeocationDetails = new BufferedReader(new InputStreamReader(geoLocationDetailXMLURLConnection.getInputStream(), "UTF-8"));
InputSource inputSource = new InputSource(geoLeocationDetails);
sp.parse(inputSource, handler);
handler.readList();
} catch (Exception e) {
e.printStackTrace();
}
我看不到错误。但它给出了 NullPointerException 错误。这是网址 =“ http://www.gold.com.tr/cok-sa tanlar-rss/54109/0 ”