Comment detail
XMLから情報を取り出す (Nested Flatten)
変数 data がありませんね。与えられた問題では 「XML文字列がすでに入手できてdataという変数に代入されている」というこですので、 InputSource は、url .openStream () ではなく、new StringReader (data) で初期化すれば良いと思います。
1 2 3 4 5 | import java.io.StringReader ;
String data = "~" ;
InputSource in = new InputSource (new StringReader (data));
|
ごもっとも。 ということで再投稿。 ただ,JavaではXMLデータをStringで扱うことは一般的ではない, というのは譲れないところなのでInputSourceを使ったものを標準とし, Stringでも大丈夫,というコードにしました。 異なる引数をとる同機能のメソッドが同名で定義され, 他を呼び出す形で実装されているのも「Javaらしい」と いうことで。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
public class GetLastBuildDate {
public static void main(String[] args) throws Exception {
URL url = new URL("http://ja.doukaku.org/feeds/comments/");
// 題意に沿ったもの
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
StringBuffer buf = new StringBuffer();
for (String s = br.readLine(); s != null; s = br.readLine()) {
buf.append(s).append("\n");
}
String data = buf.toString(); // dataにXMLを文字列として格納
System.out.println(getLastBuildDate(data));
// より「Javaらしい」方法
InputSource in = new InputSource(url.openStream()); // XMLはInputSourceで
System.out.println(getLastBuildDate(in));
}
public static String getLastBuildDate(String data) throws XPathExpressionException {
return getLastBuildDate(new InputSource(new StringReader(data)));
}
public static String getLastBuildDate(InputSource in) throws XPathExpressionException {
XPath xpath = XPathFactory.newInstance().newXPath();
String path = "//lastBuildDate";
Node node = (Node)xpath.evaluate(path, in, XPathConstants.NODE);
return node.getTextContent();
}
}
|





tnk
#712()
[
Java
]
Rating0/0=0.00
Rating0/0=0.00-0+
1 reply [ reply ]