fork download
  1. import java.io.StringReader;
  2.  
  3. import javax.xml.parsers.DocumentBuilder;
  4. import javax.xml.parsers.DocumentBuilderFactory;
  5. import javax.xml.xpath.XPath;
  6. import javax.xml.xpath.XPathConstants;
  7. import javax.xml.xpath.XPathExpression;
  8. import javax.xml.xpath.XPathFactory;
  9.  
  10. import org.w3c.dom.Document;
  11. import org.xml.sax.InputSource;
  12.  
  13. public class Main {
  14. public static void main(String[] args) throws Exception {
  15. String xml = "<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?>\r\n" + //
  16. "<REPOSITORY xmlns:LIBRARY = \"http://www.openarchives.org/LIBRARY/2.0/\" xmlns:xsi = \"http://www.w3.prg/2001/XMLSchema-instance\" xsi:schemaLocation = \"http://www.openarchives.org/LIBRARY/2.0/ http://www.openarchives.org/LIBRARY/2.0/LIBRARY-PHM.xsd\">\r\n" + //
  17. "<repository>Test</repository>\r\n" + //
  18. "<records><record>\r\n" + //
  19. "<ejemplar>\r\n" + //
  20. "<library_book:book \r\n" + //
  21. " xmlns:library_book=\"http://www.w3c.es/LIBRARY/book/\"\r\n" + //
  22. " xmlns:book=\"http://www.w3c.es/LIBRARY/book/\"\r\n" + //
  23. " xmlns:bookAssets=\"http://www.w3c.es/LIBRARY/book/\"\r\n" + //
  24. " xmlns:bookAsset=\"http://www.w3c.es/LIBRARY/book/\"\r\n" + //
  25. " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" + //
  26. " xsi:schemaLocation=\"http://www.w3c.es/LIBRARY/book/ http://www.w3c.es/LIBRARY/replacement/book.xsd\">\r\n" + //
  27. "<book:bookAssets count=\"1\">\r\n" + //
  28. "<book:bookAsset nasset=\"1\">\r\n" + //
  29. "<book:bookAsset.id>value1</book:bookAsset.id>\r\n" + //
  30. "<book:bookAsset.event>\r\n" + //
  31. "<book:bookAsset.event.id>value2</book:bookAsset.event.id>\r\n" + //
  32. "</book:bookAsset.event>\r\n" + //
  33. "</book:bookAsset>\r\n" + //
  34. "</book:bookAssets>\r\n" + //
  35. "</library_book:book>\r\n" + //
  36. "</ejemplar>\r\n" + //
  37. "</record></records>\r\n" + //
  38. "</REPOSITORY>";
  39. // Standard of reading a XML file
  40. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  41. factory.setNamespaceAware(true);
  42. DocumentBuilder builder;
  43. Document doc = null;
  44. XPathExpression expr = null;
  45. builder = factory.newDocumentBuilder();
  46. doc = builder.parse(new InputSource(new StringReader(xml)));
  47. // Create a XPathFactory
  48. XPathFactory xFactory = XPathFactory.newInstance();
  49. // Create a XPath object
  50. XPath xpath = xFactory.newXPath();
  51. expr = xpath.compile("//*[local-name()='bookAsset.event.id']/text()");
  52. Object result = expr.evaluate(doc, XPathConstants.STRING);
  53. System.out.println("RESULT=" + result);
  54. }
  55. }
  56.  
Success #stdin #stdout 0.1s 246144KB
stdin
Standard input is empty
stdout
RESULT=value2