import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class xmlTest {
private static ArrayList idList, titleList, artistList,
durationList, playsList, thumbUrlList;
public static void main(String[] args) {
idList = new ArrayList();
titleList = new ArrayList();
artistList = new ArrayList();
durationList = new ArrayList();
playsList = new ArrayList();
thumbUrlList = new ArrayList();
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean id = false;
boolean title = false;
boolean artist = false;
boolean duration = false;
boolean plays = false;
boolean thumb_url = false;
public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("ID")) {
id = true;
}
if (qName.equalsIgnoreCase("TITLE")) {
title = true;
}
if (qName.equalsIgnoreCase("ARTIST")) {
artist = true;
}
if (qName.equalsIgnoreCase("DURATION")) {
duration = true;
}
if (qName.equalsIgnoreCase("PLAYS")) {
plays = true;
}
if (qName.equalsIgnoreCase("THUMB_URL")) {
thumb_url = true;
}
}
public void characters(char ch[], int start, int length)
throws SAXException {
if (id) {
idList.add(new String(ch, start, length));
id = false;
}
if (title) {
titleList.add(new String(ch, start, length));
title = false;
}
if (artist) {
artistList.add(new String(ch, start, length));
artist = false;
}
if (duration) {
durationList.add(new String(ch, start, length));
duration = false;
}
if (plays) {
playsList.add(new String(ch, start, length));
plays = false;
}
if (thumb_url) {
thumbUrlList.add(new String(ch, start, length));
thumb_url = false;
}
}
};
URL xmlyolu = new URL("http://www.ahmettalut.com/pizza.xml");
InputStream inputStream = xmlyolu.openStream();
Reader reader = new InputStreamReader(inputStream, "UTF-8");
InputSource is = new InputSource(reader);
is.setEncoding("UTF-8");
saxParser.parse(is, handler);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(getAllInfo());
}
public static String getAllInfo() {
String allInfo = "";
for (int i = 0; i < artistList.size(); i++) {
allInfo += idList.get(i) + titleList.get(i) + artistList.get(i)
+ durationList.get(i) + playsList.get(i)
+ thumbUrlList.get(i) + "\n";
}
return allInfo;
}
}
http://ahmettalut.com/pizza.xml adresindeki xml dosyasını kullanarak yukarıdaki kod yardımı ile verileri çekebilirsiniz.
https://github.com/kilitbilgi/androidXMLParse/tree/master
adresine de örnek bir android projesini ekledim.
İyi çalışmalar.