XPath es un lenguaje que permite obtener nodos de archivos XML de una forma simple y concisa. Mediante XPath y Java podemos obtener datos de un fichero XML realizando consultas.
Clases de XPath
XPath tiene dos clases en su API, la primera XPathConstants, que es la clase que incluye constantes de XPath y la segunda, XPathFactory que es la que se encarga de crear objetos XPath cuando la instanciamos.
A continuación podemos ver un ejemplo de uso de XPathFactory, donde instanciaremos esta clase para crear objetos de la clase XPathExpression, que servirán para hacer consultas a un archivo XML.
//Creando la Instacia xPath
XPath xPath = XPathFactory.newInstance().newXPath();
//Creando la expresión con la QUERY en sintaxis XPath
XPathExpression expression = xPath.compile( QUERY );
//Ejecutando la consulta y recuperando el resultado
TYPE value = (TYPE) expression.evaluate(DOCUMENTO_XML, XPathConstants.TYPE);
Una consulta de este tipo puede devolver varios tipos de datos, ya pueden ser NUMBER, BOOLEAN, STRING, NODE (devuelve un objeto Node con los atributos y nodos hijos de un nodo XML) y NODESET (una lista de Node).
Ejemplo de XPath en Java
Archivo books.xml
Fichero Main.java
import java.io.File;
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.Document;
import org.w3c.dom.NodeList;
/**
*
* @author tunatore
*/
public class Main {
public static void main(String[] args) throws Exception {
//loading the XML document from a file
DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();
builderfactory.setNamespaceAware(true);
DocumentBuilder builder = builderfactory.newDocumentBuilder();
Document xmlDocument = builder.parse(
new File(Main.class.getResource("books.xml").getFile().replace("%20", " ")));
XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance();
XPath xPath = factory.newXPath();
//getting the name of the book having an isbn number == ABCD7327923
String isbnNum = "ABCD7327923";
XPathExpression xPathExpression = xPath.compile("//LIBRARY//BOOKS//BOOK[@isbn='" +isbnNum + "']//NAME");
String nameOfTheBook = xPathExpression.evaluate(xmlDocument,XPathConstants.STRING).toString();
System.out.println("name of the Book ---> " + nameOfTheBook);
//getting all authors for the book having an isbn number == ABCD7327923
xPathExpression = xPath.compile("//LIBRARY//BOOKS//BOOK[@isbn='" +isbnNum + "']//AUTHORS//AUTHOR");
NodeList nodeListBook = (NodeList) xPathExpression.evaluate(xmlDocument,XPathConstants.NODESET);
System.out.println("Total number of authors for the book " + nameOfTheBook + " is --> " + nodeListBook.getLength());
for (int index = 0; index < nodeListBook.getLength(); index++) {
String author = nodeListBook.item(index).getTextContent();
System.out.println("Author " + (index + 1) + " ---> " + author);
}
//getting all tags for the dvd having id == 3213324
String dvdID = "3213324";
xPathExpression = xPath.compile("//LIBRARY//DVDS//DVD[@id='" +dvdID + "']");
NodeList nodeDVD = (NodeList) xPathExpression.evaluate(xmlDocument,XPathConstants.NODESET);
NodeList nodeListForDVD = nodeDVD.item(0).getChildNodes();
for (int index = 0; index < nodeDVD.item(0).getChildNodes().getLength(); index++) {
String tagName = nodeListForDVD.item(index).getNodeName();
String tagValue = nodeListForDVD.item(index).getTextContent();
if(!tagName.equals("#text")) //handling empty comment (#text)
System.out.println(tagName + " value ---> " + tagValue);
}
}
}
Este código nos daria como resultado lo siguiente:
name of the Book —> Java Programing
Total number of authors for the book Java Programing is –> 3
Author 1 —> Tuna TORE
Author 2 —> Linus Torvalds
Author 3 —> James Gosling
NAME value —> Natural Science
CONTENT value —> Science
AUTHORS value —>
John Green
Bill Gates
Y este es el uso que podemos darle a XPath en Java, pudiendo obtener datos de documentos XML de una forma relativamente sencilla.
Deja un comentario