Xpath with java, extract name

1

I'm starting with Xpath in java and I'm trying to get information from xml tags through Xpath queries. I can not articulate a query that shows me the name of people with a weight over 100.

So far the code I have is ::

package ejemplo_xpath;
import java.io.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.*;
import org.w3c.dom.*;

import org.xml.sax.InputSource;

public class consultaXPath {

    XPathExpression exp;
    Element element;
    Document XMLDoc;
    XPath xpath;

    public int abrir_file_DOM()
    {
        //Abre un fichero XML para crear un DOM
        try {
            //El fichero XML que se abre es LibrosXML.xml almacenado en la carperta del proyecto.
            xpath = XPathFactory.newInstance().newXPath();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            XMLDoc = factory.newDocumentBuilder().parse(new InputSource(new
            FileInputStream("/home/usuario/ACCESO A DATOS/nombres1.xml")));
            //Al llegar aquí ya se ha creado la estructura DOM para se consultada
            return 0;
        }
        catch (Exception ex) {
            System.out.println("Error: " + ex.toString());
            return -1;
        }

    }
    public int Ejecutar_XPath()
    {

        String salida = "";
    try {
        //Crea el objeto XPathFactory 
         xpath = XPathFactory.newInstance().newXPath();
        //Crea un objeto DocumentBuilderFactory para el DOM (JAXP) 
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

         Document XMLDoc = factory.newDocumentBuilder().parse(new InputSource(new FileInputStream("/home/Escritorio/peso.xml")));
        //Crea un XPathExpression con la consulta deseada
         exp = xpath.compile("/identificacion/*/nombre");
        //Ejecuta la consulta indicando que se ejecute sobre el DOM y que devolverá 
        //el resultado como una lista de nodos.
         Object result= exp.evaluate(XMLDoc, XPathConstants.NODESET);
         NodeList nodeList = (NodeList) result;

        //Ahora recorre la lista para sacar los resultados
         for (int i = 0; i < nodeList.getLength(); i++) {
          salida = salida + "\n" + 
         nodeList.item(i).getChildNodes().item(0).getNodeValue();
         }
          System.out.println(salida);
          return 0;
          }
          catch (Exception ex) {
          System.out.println("Error: " + ex.toString());
          return -1;
          }


}

}

The xml is

 <paciente>  
   <identificacion>  
    <nombre>juan</nombre>  
    <Peso>143 </Peso>  
   </identificacion>    
   <identificacion>  
    <nombre>daniel</nombre>  
    <Peso>343 </Peso>   
   </identificacion>   
 </paciente>
    
asked by Juan 23.10.2018 в 12:27
source

1 answer

1

To retrieve the names of people with a weight greater than 100, it would be:

/paciente/identificacion[Peso>100]/nombre

    
answered by 23.10.2018 / 13:16
source