What is it ?
The xPath allows us to select only a part of our document using a very similar syntax to the folder structure of our operating system. To facilitate the pursuit of our document data.
Why use it ?
With the help of xPath we do not need to add many ifs in the code that reads our xml file which greatly facilitates the process of filtering data from an XML file to generate various reports for example.
Example:
List<Product> products = new ArrayList<Produto>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("src/sale.xml");
XPath xPath = XPathFactory.newInstance().newXPath();
String ex = "/sale/products/product[2]";
XPathExpression xPathExpression = xPath.compile(expression);
NodeList result = (NodeList)
xPathExpression.evaluate(document, XPathConstants.NODESET);
for(int i = 0; i < result.getLength();i++) {
Element product = (Element) result.item(i);
String name = product.getElementsByTagName("name")
.item(0).getTextContent();
Double price = Double.parseDouble(product
.getElementsByTagName("price").item(0).getTextContent());
Product prod = new Product();
prod.setName(name);
prod.setPrice(price);
products.add(prod);
}
System.out.println(products);