Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- introducir el código aquí package ejemplo_xpath;
- 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;
- }
Add Comment
Please, Sign In to add comment