The usage of Xpath

If you want to use the Xpath thing when you face the situation that you need to parse the xml thing, then You don’t have to import any dependencies because this function is occured from basic java. I think it’s best point of this library.

1. Get XML String from the URL using HttpConnection.

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

public String getXml(String urlStr) {

String result = "";

try {
URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line;

while((line = br.readLine()) != null) {
result += line.trim();
}
} catch(MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return result;

}

You can get the xml file using the above thing.

2. Transform XML String to Document Object.

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

private Document getDocument(String xml) {

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document document = null;

try {

InputSource is = new InputSource(new StringReader(xml));
builder = factory.newDocumentBuilder();
document = builder.parse(is);

} catch(ParserConfigurationException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} catch(SAXException e) {
e.printStackTrace();
}

return document;

}

Actually Document object is same thing with DOM Object in html. so you can use this object like the DOM thing.

3. Parse Document using XPath

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

private NodeList getNodeList(Document document, String expression) {

NodeList nodeList = null;

try {
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
XPathExpression expr = xPath.compile(expression);

nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

} catch(XPathExpressionException e) {
e.printStackTrace();
}

return nodeList;

}

4. Main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

String urlStr = "urlStr";

String xml = getXml(urlStr);
Document document = getDocument(xml);
NodeList nodeList = getNodeList(document, "expression");

for(int i=0; i<nodeList.getLength(); i++) {
System.out.println(node.getNodeName());
System.out.println(node.getLocalName());
System.out.println(node.getNodeType());
System.out.println(node.getTextContent());
System.out.println(node.getPrefix());
System.out.println(node.getAttributes().item(0));
}

Share