Guest User

Untitled

a guest
Oct 23rd, 2018
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. introducir el código aquí package ejemplo_xpath;
  2.  
  3. XPathExpression exp;
  4. Element element;
  5. Document XMLDoc;
  6. XPath xpath;
  7.  
  8. public int abrir_file_DOM()
  9. {
  10. //Abre un fichero XML para crear un DOM
  11. try {
  12. //El fichero XML que se abre es LibrosXML.xml almacenado en la carperta del proyecto.
  13. xpath = XPathFactory.newInstance().newXPath();
  14. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  15. XMLDoc = factory.newDocumentBuilder().parse(new InputSource(new
  16. FileInputStream("/home/usuario/ACCESO A DATOS/nombres1.xml")));
  17. //Al llegar aquí ya se ha creado la estructura DOM para se consultada
  18. return 0;
  19. }
  20. catch (Exception ex) {
  21. System.out.println("Error: " + ex.toString());
  22. return -1;
  23. }
  24.  
  25. }
  26. public int Ejecutar_XPath()
  27. {
  28.  
  29. String salida = "";
  30. try {
  31. //Crea el objeto XPathFactory
  32. xpath = XPathFactory.newInstance().newXPath();
  33. //Crea un objeto DocumentBuilderFactory para el DOM (JAXP)
  34. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  35.  
  36. Document XMLDoc = factory.newDocumentBuilder().parse(new InputSource(new FileInputStream("/home/Escritorio/peso.xml")));
  37. //Crea un XPathExpression con la consulta deseada
  38. exp = xpath.compile("/identificacion/*/nombre");
  39. //Ejecuta la consulta indicando que se ejecute sobre el DOM y que devolverá
  40. //el resultado como una lista de nodos.
  41. Object result= exp.evaluate(XMLDoc, XPathConstants.NODESET);
  42. NodeList nodeList = (NodeList) result;
  43.  
  44. //Ahora recorre la lista para sacar los resultados
  45. for (int i = 0; i < nodeList.getLength(); i++) {
  46. salida = salida + "n" +
  47. nodeList.item(i).getChildNodes().item(0).getNodeValue();
  48. }
  49. System.out.println(salida);
  50. return 0;
  51. }
  52. catch (Exception ex) {
  53. System.out.println("Error: " + ex.toString());
  54. return -1;
  55. }
Add Comment
Please, Sign In to add comment