import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
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.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
public class JavaParser extends DefaultHandler{
private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
private boolean inUrl = false;
private boolean inTitle = false;
private boolean inDescription = false;
private boolean inItem = false;
private boolean inDate = false;
private String title = null;
private StringBuffer description = new StringBuffer();
private String date = null;
private String imageUrl;
public void config()
{
try {
InputStream inputStream=new URL(url).openStream();
Reader reader = new InputStreamReader(inputStream,"UTF-8");
InputSource is = new InputSource(reader);
is.setEncoding("UTF-8");
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlReader = parser.getXMLReader();
// IotdHandler handler=new IotdHandler();
xmlReader.setContentHandler(this);
// InputStream inputStream = new URL(url).openStream();
xmlReader.parse(is);
// parser.parse(is, this);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
if (localName.equals("enclosure"))
{ inUrl = true;
imageUrl=attributes.getValue("url");
System.out.println(imageUrl);
}
else { inUrl = false; }
if (localName.startsWith("item"))
{ inItem = true; }
else if (inItem) {
if (localName.equals("title"))
{ inTitle = true;
System.out.println("invtitle");}
else { inTitle = false; }
if (localName.equals("description"))
{ inDescription = true;
System.out.println("indiscription");}
else { inDescription = false; }
if (localName.equals("pubDate"))
{ inDate = true;
System.out.println("dtae");}
else { inDate = false; }
}
}
public void characters(char ch[], int start, int length) {
String chars = new String(ch).substring(start, start + length);
if (inTitle && title == null) { title = chars; }
if (inDescription) { description.append(chars); }
if (inDate && date == null) { date = chars; }
}
public String getTitle() { return title; }
public StringBuffer getDescription() { return description; }
public String getDate() { return date; }
public static void main(String[] args) {
JavaParser parse=new JavaParser();
parse.config();
System.out.println(parse.getTitle());
}
}
この XML ファイルを読み込んで Title の値を取得したいのですが、これは私が試していたコードですが、title に null 値を返していますそうしないと、MalformedByteSequenceException がスローされたためです。