forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaXPathSimpleEx.java
More file actions
42 lines (30 loc) · 1.3 KB
/
JavaXPathSimpleEx.java
File metadata and controls
42 lines (30 loc) · 1.3 KB
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
37
38
39
40
41
42
package com.zetcode;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
public class JavaXPathSimpleEx {
// XPath syntax: https://devhints.io/xpath
/* TODO
get second user
get all users
get id attribute of last user
*/
public static void main(String[] args) throws ParserConfigurationException, IOException,
SAXException, XPathExpressionException {
var factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // required
var builder = factory.newDocumentBuilder();
var doc = builder.parse("src/main/resources/users.xml");
var xPathFactory = XPathFactory.newInstance();
var xpath = xPathFactory.newXPath();
var expr = xpath.compile("/users/user[1]/firstname/text()");
var firstName = expr.evaluate(doc, XPathConstants.STRING);
expr = xpath.compile("/users/user[1]/lastname/text()");
var lastName = expr.evaluate(doc, XPathConstants.STRING);
System.out.printf("The first user is %s %s%n", firstName, lastName);
}
}