I was pleasantly surprised when I needed to do some XPath in Java recently - it's been a while since I did any and I was expecting some potentially tedious 3rd party integration. Turns out it's now all included in the standard JDK and extracting the data we need from an online resource that looks like this ...
...
Was simply a case of doing this ...
// get connection to items service
URL itemsUrl = new URL(ITEMS_URI);
URLConnection itemsConnection = itemsUrl.openConnection();
// use xpath to extract the item ID's
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(itemsConnection.getInputStream());
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression xpathExpression = xpath.compile("/guides/r/a[@n=\"ItemId\"]/@v");
// create the list of item ID's
List<Long> itemIds = new ArrayList<Long>();
Object result = xpathExpression.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
String itemId = nodes.item(i).getNodeValue();
try {
itemIds.add(Long.parseLong(itemId));
} catch (NumberFormatException e) {
System.out.println("Could not parse item ID: " + itemId);
}
}
return itemIds;
I'm probably being more specific than I need to be there, but I'm not 100% sure what the finished format will look like.
No comments:
Post a Comment