Created
December 7, 2016 09:58
-
-
Save gn-spawn/656f822aab4991315937e8debafb0ecc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ex5; | |
import org.w3c.dom.Document; | |
import org.w3c.dom.NodeList; | |
import org.xml.sax.SAXException; | |
import javax.xml.parsers.DocumentBuilderFactory; | |
import javax.xml.parsers.ParserConfigurationException; | |
import javax.xml.xpath.XPath; | |
import javax.xml.xpath.XPathConstants; | |
import javax.xml.xpath.XPathExpressionException; | |
import javax.xml.xpath.XPathFactory; | |
import java.io.IOException; | |
public class TitleSearcherByXPath { | |
public static void main(String[] args) { | |
TitleSearcherByXPath titleSearcherByXPath = new TitleSearcherByXPath(); | |
titleSearcherByXPath.showItemListByXpath("ちょまど"); | |
} | |
private void showItemListByXpath(String searchWord) { | |
try { | |
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); | |
final String RSS_URL = "http://b.hatena.ne.jp/hotentry.rss"; | |
Document document = documentBuilderFactory.newDocumentBuilder().parse(RSS_URL); | |
// Xpathのインスタンス生成 | |
XPathFactory factory = XPathFactory.newInstance(); | |
XPath xpath = factory.newXPath(); | |
// 要素を取得 | |
// String location = "/rss/channel/item"; | |
NodeList itemNodeList = (NodeList)xpath.evaluate("/RDF/item/title", | |
document, XPathConstants.NODESET); | |
// RSS 2.0 | |
if(itemNodeList.getLength() == 0) | |
itemNodeList = (NodeList)xpath.evaluate("/rss/channel/item/title", | |
document, XPathConstants.NODESET); | |
for(int i = 0; i < itemNodeList.getLength(); i++) { | |
String title = itemNodeList.item(i).getFirstChild().getNodeValue(); | |
if (title.contains(searchWord)) { | |
System.out.println(title); | |
} | |
} | |
} catch (IOException | XPathExpressionException | SAXException | ParserConfigurationException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment