Java HTML / XML How to - Get data from XML vis URL using XPath








Question

We would like to know how to get data from XML vis URL using XPath.

Answer

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
//w  ww . j av  a  2  s  .  c  o  m
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
  public static void main(String[] args) throws Exception {
    getHTTPXml(new URL("http://your site/details.xml"));
  }

  static void getHTTPXml(URL url) throws Exception {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("ACCEPT", "application/xml");
    InputStream xml = conn.getInputStream();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    org.w3c.dom.Document document = builder.parse(xml);

    System.out.println(document);
    String doctype = conn.getContentType();
    System.out.println(doctype);

    XPathFactory pathFactory = XPathFactory.newInstance();
    XPath path = pathFactory.newXPath();
    XPathExpression expression;
    expression = path.compile("/result/checkid");
    NodeList nodeList = (NodeList) expression.evaluate(document,
        XPathConstants.NODESET);
    String checkids[] = getNodeValue(nodeList);
    for (String checkid : checkids) {
      System.out.print(checkid + ", ");
    }
    conn.disconnect();
  }
  static String[] getNodeValue(NodeList nodes) {
    String checkIds[] = new String[nodes.getLength()];
    for (int i = 0; i < nodes.getLength(); i++) {
      Node node = nodes.item(i);
      checkIds[i] = node.getTextContent();
    }
    return checkIds;
  }
}