This comment is reply for 971 匿名: 変数 data がありませんね。与えられ...(XMLから情報を取り出す). Go to thread root.
tnk #1089(2007/07/19 02:17 GMT) [ Java ] Rating1/1=1.00
ごもっとも。 ということで再投稿。 ただ,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(); } }
Rating1/1=1.00-0+
[ reply ]
tnk
#1089()
[
Java
]
Rating1/1=1.00
Rating1/1=1.00-0+