Wednesday, June 29, 2011

XPath by example :D, next stop XSLT…

Pruebas usando XPath para después pasar a usar XSLT. Ejemplo simple para hacer consultas sobre un XML vía XPath:D


 1  
2 import java.io.File;
3
4 import java.io.FileInputStream;
5
6 import java.io.FileNotFoundException;
7
8 import javax.xml.xpath.XPath;
9 import javax.xml.xpath.XPathExpression;
10 import javax.xml.xpath.XPathExpressionException;
11 import javax.xml.xpath.XPathFactory;
12
13 import org.xml.sax.InputSource;
14
15 public class XpathTester {
16
17 public static void main(String[] args)
18 throws XPathExpressionException,FileNotFoundException {
19
20 System.out.println(":) File" );
21 XPathFactory factory=XPathFactory.newInstance();
22 XPath xPath=factory.newXPath();
23
24 //Let’s assume you are interested in compiling
25 //the XPath expression /catalog/journal/
26 //article[@date='January-2004']/title, which
27 //addresses title elements within all article
28 //elements with the date attribute set to January-2004.
29 //You can do so with the compile() method of the
30 //XPath object, as shown here:
31
32 XPathExpression xPathExpression=
33 xPath.compile("//article[ancestor::journal[@title='Java Technology']] ");
34
35 //This compile() method returns an XPathExpression object.
36 //If the XPath expression has an error,
37 //an XPathExpressionException gets generated.
38
39 File xmlDocument = new File("test.xml");
40 InputSource inputSource = new InputSource(new FileInputStream(xmlDocument));
41
42 String title =xPathExpression.evaluate(inputSource);
43 System.out.println(title) ;
44
45 }
46
47 public XpathTester() {
48 super();
49 }
50 }

Oracle SOA Suite 11g.