{"id":42673,"date":"2016-12-26T11:00:35","date_gmt":"2016-12-26T09:00:35","guid":{"rendered":"http:\/\/examples.javacodegeeks.com\/?p=42673"},"modified":"2016-12-24T19:39:20","modified_gmt":"2016-12-24T17:39:20","slug":"java-xpath-examples","status":"publish","type":"post","link":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/","title":{"rendered":"Java XPath Examples"},"content":{"rendered":"<h2>1. Introduction<\/h2>\n<p>The previous article, Java XPath Best Practices Tutorial (<a href=\"http:\/\/examples.javacodegeeks.com\/core-java\/xpath-best-practices-tutorial\/\" target=\"_blank\">https:\/\/examples.javacodegeeks.com\/core-java\/xpath-best-practices-tutorial\/<\/a>), explored how to set up a Java application to create a DOM (Document Object Model) document using a DOM parser to read an XML file; and an XPath object to evaluate XPath expressions as applied to the DOM.<\/p>\n<p>This article dives into how to construct XPath expressions. Starting with the syntax used to build XPath expressions, and ending with some examples sum up the concepts explored.<\/p>\n<p>The download for this article includes both the inventory.xml file used in the previous article and also includes the complete source code for a simple Java console application, called XPath Expression Explorer. More details about XPath Expression Explorer revealed throughout this article.<\/p>\n<h2>2. XPath Expression Explorer<\/h2>\n<p>This article builds and uses a Java application (XPath Expression Explorer) to reveal facts about XPath expressions and to help shorten the learning curve encountered when learning XPath expressions.<\/p>\n<h3>2.1 The Data<\/h3>\n<p>Below is the inventory.xml file from the previous article.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>inventory.xml<\/em><\/span><\/p>\n<pre class=\"brush:xml\">&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\r\n&lt;inventory&gt;\r\n    &lt;vendor name=\"Dell\"&gt;\r\n        &lt;computer&gt;\r\n            &lt;model&gt;Win 10 Laptop&lt;\/model&gt;\r\n            &lt;os&gt;Windows 10&lt;\/os&gt;\r\n            &lt;cpu&gt;Intel i7&lt;\/cpu&gt;\r\n            &lt;ram&gt;12GB&lt;\/ram&gt;\r\n            &lt;price&gt;900.00&lt;\/price&gt;\r\n        &lt;\/computer&gt;\r\n        &lt;computer&gt;\r\n            &lt;model&gt;Low Cost Windows Laptop&lt;\/model&gt;\r\n            &lt;os&gt;Windows 10 Home&lt;\/os&gt;\r\n            &lt;cpu&gt;Intel Pentium&lt;\/cpu&gt;\r\n            &lt;ram&gt;4GB&lt;\/ram&gt;\r\n            &lt;price&gt;313.00&lt;\/price&gt;\r\n        &lt;\/computer&gt;\r\n        &lt;computer&gt;\r\n            &lt;model&gt;64 Bit Windows Desktop Computer&lt;\/model&gt;\r\n            &lt;os&gt;Windows 10 Home 64 Bit&lt;\/os&gt;\r\n            &lt;cpu&gt;AMD A8-Series&lt;\/cpu&gt;\r\n            &lt;ram&gt;8GB&lt;\/ram&gt;\r\n            &lt;price&gt;330.00&lt;\/price&gt;\r\n        &lt;\/computer&gt;\r\n    &lt;\/vendor&gt;\r\n    &lt;vendor name=\"Apple\"&gt;\r\n        &lt;computer&gt;\r\n            &lt;model&gt;Apple Desktop Computer&lt;\/model&gt;\r\n            &lt;os&gt;MAC OS X&lt;\/os&gt;\r\n            &lt;cpu&gt;Intel Core i5&lt;\/cpu&gt;\r\n            &lt;ram&gt;8GB&lt;\/ram&gt;\r\n            &lt;price&gt;1300.00&lt;\/price&gt;\r\n        &lt;\/computer&gt;\r\n        &lt;computer&gt;\r\n            &lt;model&gt;Apple Low Cost Desktop Computer&lt;\/model&gt;\r\n            &lt;os&gt;OS X Yosemite&lt;\/os&gt;\r\n            &lt;cpu&gt;4th Gen Intel Core i5&lt;\/cpu&gt;\r\n            &lt;ram&gt;8GB&lt;\/ram&gt;\r\n            &lt;price&gt;700.00&lt;\/price&gt;\r\n        &lt;\/computer&gt;\r\n    &lt;\/vendor&gt;\r\n    &lt;vendor name=\"HP\"&gt;\r\n        &lt;computer&gt;\r\n            &lt;model&gt;HP Low Cost Windows 10 Laptop&lt;\/model&gt;\r\n            &lt;os&gt;Windows 10 Home&lt;\/os&gt;\r\n            &lt;cpu&gt;AMD A6-Series&lt;\/cpu&gt;\r\n            &lt;ram&gt;4GB&lt;\/ram&gt;\r\n            &lt;price&gt;230.00&lt;\/price&gt;\r\n        &lt;\/computer&gt;\r\n        &lt;computer&gt;\r\n            &lt;model&gt;Windows 7 Desktop&lt;\/model&gt;\r\n            &lt;os&gt;Windows 7&lt;\/os&gt;\r\n            &lt;cpu&gt;6th Gen Intel Core i5&lt;\/cpu&gt;\r\n            &lt;ram&gt;6GB&lt;\/ram&gt;\r\n            &lt;price&gt;750.00&lt;\/price&gt;\r\n        &lt;\/computer&gt;\r\n        &lt;computer&gt;\r\n            &lt;model&gt;HP High End, Low Cost 64 Bit Desktop&lt;\/model&gt;\r\n            &lt;os&gt;Windows 10 Home 64 Bit&lt;\/os&gt;\r\n            &lt;cpu&gt;6th Gen Intel Core i7&lt;\/cpu&gt;\r\n            &lt;ram&gt;12GB&lt;\/ram&gt;\r\n            &lt;price&gt;800.00&lt;\/price&gt;\r\n        &lt;\/computer&gt;\r\n    &lt;\/vendor&gt;\r\n&lt;\/inventory&gt;\r\n\r\nA.   There are 3 vendors; each vendor has a unique name\r\nB.   There are 8 computers defined\r\nC.   Each computer node has 5 children: \r\n     * model \u2013 Name of this configuration\r\n     * os \u2013 Name of Operating System installed\r\n     * cpu \u2013 Type of processor\r\n     * ram \u2013 size of installed RAM\r\n     * price \u2013 expressed as a decimal number\r\n<\/pre>\n<h3>2.2 The Application<\/h3>\n<p>Below is the Java code that comprises the XPath Expression Explorer console application.<\/p>\n<p><span style=\"text-decoration: underline;\"><em>JavaXPathExpressionExplorer.java<\/em><\/span><\/p>\n<pre class=\"brush:java\">import java.io.BufferedReader;\r\nimport java.io.IOException;\r\nimport java.io.InputStreamReader;\r\nimport javax.xml.parsers.DocumentBuilder;\r\nimport javax.xml.parsers.DocumentBuilderFactory;\r\nimport javax.xml.parsers.ParserConfigurationException;\r\nimport javax.xml.xpath.XPath;\r\nimport javax.xml.xpath.XPathConstants;\r\nimport javax.xml.xpath.XPathExpressionException;\r\nimport javax.xml.xpath.XPathFactory;\r\n\r\nimport org.w3c.dom.Document;\r\nimport org.w3c.dom.Node;\r\nimport org.w3c.dom.NodeList;\r\n\r\nimport org.xml.sax.SAXException;\r\n\r\npublic class JavaXPathExpressionExplorer {\r\n\r\n    public static final String DEFAULT_XML_FILENAME = \"inventory.xml\";\r\n\r\n    public static void main(String... args) {\r\n\r\n        \/\/ Setup an InputStreamReader to read from the keyboard\r\n        InputStreamReader reader = new InputStreamReader(System.in);\r\n        BufferedReader in = new BufferedReader(reader);\r\n\r\n        \/\/ Instantiate the factory that supplies the DOM parser\r\n        DocumentBuilderFactory builderFactory =\r\n                DocumentBuilderFactory.newInstance();\r\n\r\n        DocumentBuilder domParser = null;\r\n        try {\r\n            \/\/ Instantiate the DOM parser\r\n            domParser = builderFactory.newDocumentBuilder();\r\n\r\n            \/\/ Load the DOM Document from the XML data using the parser\r\n            Document domDocument =\r\n                    domParser.parse(getFileInputStreamName(in));\r\n\r\n            \/\/ Instantiate an XPath object which compiles\r\n            \/\/ and evaluates XPath expressions.\r\n            XPath xPath = XPathFactory.newInstance().newXPath();\r\n\r\n            while (true) {\r\n\r\n                System.out.print(\"Enter expression (blank line to exit): \");\r\n                String expr = in.readLine(); \/\/ Holds the XPath expression\r\n\r\n                try {\r\n                    if ((expr == null) || (expr.length() == 0)) {\r\n                        System.exit(0); \/\/ User is done entering expressions\r\n                    }\r\n                    System.out.println(expr + \" evaluates to:\");\r\n\r\n                    \/\/ See if expr evaluates to a String\r\n                    String resString = (String) xPath.compile(expr).\r\n                        evaluate(domDocument, XPathConstants.STRING);\r\n                    if (resString != null) {\r\n                        System.out.println(\"String: \" + resString);\r\n                    }\r\n\r\n                    Number resNumber = (Number) xPath.compile(expr).\r\n                        evaluate(domDocument, XPathConstants.NUMBER);\r\n                    if (resNumber != null) {\r\n                        System.out.println(\"Number: \" + resNumber);\r\n                    }\r\n\r\n                    Boolean resBoolean = (Boolean) xPath.compile(expr).\r\n                        evaluate(domDocument, XPathConstants.BOOLEAN);\r\n                    if (resNumber != null) {\r\n                        System.out.println(\"Boolean: \" + resBoolean);\r\n                    }\r\n\r\n                    Node resNode = (Node) xPath.compile(expr).\r\n                        evaluate(domDocument, XPathConstants.NODE);\r\n                    if (resNode != null) {\r\n                        System.out.println(\"Node: \" + resNode);\r\n                    }\r\n\r\n                    NodeList resNodeList = (NodeList) xPath.compile(expr).\r\n                        evaluate(domDocument, XPathConstants.NODESET);\r\n                    if (resNodeList != null) {\r\n                        int lenList = resNodeList.getLength();\r\n                        System.out.println(\"Number of nodes in NodeList: \" + lenList);\r\n                        for (int i = 1; i &lt;= lenList; i++) {\r\n                            resNode = resNodeList.item(i-1);\r\n                            String resNodeNameStr = resNode.getNodeName();\r\n                            String resNodeTextStr = resNode.getTextContent();\r\n                            System.out.println(i + \": \" + resNode + \"  (NodeName:'\" +\r\n                                resNodeNameStr + \"'    NodeTextContent:'\" + \r\n                                resNodeTextStr + \"')\");\r\n                        }\r\n                    }\r\n                    outputSeparator();\r\n\r\n                } catch (XPathExpressionException e) {\r\n                    \/\/ Do nothing. This prevents output to console if \r\n                    \/\/ expression result type is not appropriate\r\n                    \/\/ for the XPath expression being compiled and evaluated\r\n                }\r\n\r\n            } \/\/ end  while (true)\r\n\r\n        } catch (SAXException e) {\r\n            \/\/ Even though we are using a DOM parser a SAXException is thrown\r\n            \/\/ if the DocumentBuilder cannot parse the XML file\r\n            e.printStackTrace();\r\n        } catch (IOException e) {\r\n            e.printStackTrace();\r\n        } catch (ParserConfigurationException e){\r\n                e.printStackTrace();\r\n        }\r\n    }\r\n\r\n    \/\/ Helper method to load the XML file into the DOM Document\r\n    public static String getFileInputStreamName(BufferedReader inputReader) {\r\n        System.out.print(\"Enter XML file name (abc.xml) \u201c+ \r\n            \u201cor leave blank to use \"+DEFAULT_XML_FILENAME+\": \");\r\n        String fileName = null;\r\n        try {\r\n            fileName = inputReader.readLine();\r\n        } catch (IOException e) {\r\n            e.printStackTrace();\r\n        }\r\n        if ((fileName == null) || (fileName.length() == 0)) {\r\n            return DEFAULT_XML_FILENAME;\r\n        }\r\n        return fileName;\r\n    }\r\n\r\n    \/\/ Helper method to pretty up the output\r\n    public static void outputSeparator() {\r\n        System.out.println(\"=+=+=+=+=+=+=+=+\");\r\n    }\r\n\r\n}\r\n<\/pre>\n<p>The application initially prompts the user for an XML filename. Respond to this prompt with a blank line to use the inventory.xml file found in the application\u2019s classpath.<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<p>The application then takes an XPath expression entered from the keyboard, compiles, and evaluates the expression using different return types (as determined by XPathConstants) and displays the results to the user.<\/p>\n<p>The main loop in this application repeatedly prompts for XPath expressions. Entering a blank line terminates the application.<\/p>\n<p>Admittedly the application is crude, but it is effective for learning about XPath expressions.<\/p>\n<h2>3. XPath Expressions<\/h2>\n<h3>3.1 XPathConstants Effect on XPath Expressions<\/h3>\n<p>The evaluate() method of an XPath object allows the user to specify an optional XPathConstant which determines the data type of the result returned, which changes the value of the result.<\/p>\n<p>NOTE: If the optional XPathConstant is not passed to evaluate(), the data type of the result returned by evaluate() is String.<\/p>\n<p>The table below shows the effects of the different XPathConstants when the XPath expression \/inventory\/vendor\/computer\/cpu[text() = &#8220;Intel Pentium&#8221;] is evaluated given a DOM built from the inventory.xml file (noted in section 2.1 The Data)<\/p>\n<p><span style=\"text-decoration: underline;\"><em>Table showing effects of different XPathConstants<\/em><\/span><\/p>\n<pre class=\"brush:bash\">XPath Constant          Java Data Type    Value Returned\r\n\r\nXPathConstant.String    String            Intel Pentium\r\nXPathConstant.Number    Number            NaN\r\nXPathConstant.Boolean   Boolean           true\r\nXPathConstant.Node      Node              [cpu: null]\r\nXPathConstant.NodeList  NodeList          [cpu: null]\r\n<\/pre>\n<p>It is worth noting: Using the NodeList on line 7:<\/p>\n<ul>\n<li>Executing the getNodeName() method returns the String \u201ccpu\u201d<\/li>\n<li>Executing the getNodeValue() method returns the String \u201cIntel Pentium\u201d<br \/>\n(namely, the same value as shown on line 1)<\/li>\n<\/ul>\n<p>This is shown in the code below, which has been excerpted from the XPath Expression Explorer:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>Excerpt from JavaXPathExpressionExplorer.java<\/em><\/span><\/p>\n<pre class=\"brush:java\"> NodeList resNodeList = (NodeList) xPath.compile(expr).\r\nevaluate(domDocument, XPathConstants.NODESET);\r\n if (resNodeList != null) {\r\n     int lenList = resNodeList.getLength();\r\n     System.out.println(\"Number of nodes in NodeList: \" + lenList);\r\n     for (int i = 1; i &lt;= lenList; i++) {\r\n         resNode = resNodeList.item(i-1);\r\n         String resNodeNameStr = resNode.getNodeName();\r\n         String resNodeTextStr = resNode.getTextContent();\r\n         System.out.println(i + \": \" + resNode + \r\n             \"  (NodeName:'\" + resNodeNameStr + \r\n             \"'    NodeTextContent:'\" + resNodeTextStr + \"')\");\r\n     }\r\n }\r\n<\/pre>\n<p>Which renders the following output when executed:<\/p>\n<p><span style=\"text-decoration: underline;\"><em>Output from code excerpt, above<\/em><\/span><\/p>\n<pre class=\"brush:bash\">Number of nodes in NodeList: 1\r\n1: [cpu: null]  (NodeName:'cpu'    NodeTextContent:'Intel Pentium')\r\n<\/pre>\n<h3>3.2 XPath Expression Syntax<\/h3>\n<p>DOM documents represent XML data as a tree structure. XPath expressions are a series of steps, or paths through the tree where each step specifies a Node or a set of nodes (NodeList) from the tree.<\/p>\n<p>Each step comes from one of the following categories:<\/p>\n<h4>Node specifications<\/h4>\n<p>*matches any element node<\/p>\n<table>\n<tbody>\n<tr>\n<td>\/<\/td>\n<td>specifies the root node, which is the first node in the tree<\/td>\n<\/tr>\n<tr>\n<td>\/\/<\/td>\n<td>specifies nodes in the tree that matches the selection regardless of location within the tree<\/td>\n<\/tr>\n<tr>\n<td>.<\/td>\n<td>specifies the current node<\/td>\n<\/tr>\n<tr>\n<td>..<\/td>\n<td>specifies the parent of the current node<\/td>\n<\/tr>\n<tr>\n<td>nodename<\/td>\n<td>specifies all nodes in the tree with the name &#8220;nodename&#8221;<\/td>\n<\/tr>\n<tr>\n<td>@<\/td>\n<td>specifies attributes within the node<\/td>\n<\/tr>\n<tr>\n<td>@*<\/td>\n<td>matches any node with any attribute<\/td>\n<\/tr>\n<tr>\n<td>node()<\/td>\n<td>matches any node of any kind<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h4>Predicates<\/h4>\n<p>Predicates are used to select specific nodes and are always surrounded by square brackets \u2018[]\u2019<br \/>\nExamples of some predicates are:<\/p>\n<table>\n<tbody>\n<tr>\n<td>\/vendor\/computer[1]<\/td>\n<td>Selects the first computer node that is the child of a vendor node<\/td>\n<\/tr>\n<tr>\n<td>\/vendor\/computer[last()]<\/td>\n<td>Selects the last computer node that is a child of a vendor node<\/td>\n<\/tr>\n<tr>\n<td>\/vendor\/computer[last()-1]<\/td>\n<td>Selects the computer before the last computer which is a child of a vendor<\/td>\n<\/tr>\n<tr>\n<td>\/vendor\/computer[position()350.00]<\/td>\n<td>Selects all the computer nodes of any vendor with a price value greater than 350.00<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h4>Axes<\/h4>\n<p>XPath axes specify set of Nodes relative to the current node.<\/p>\n<table>\n<tbody>\n<tr>\n<td>ancestor<\/td>\n<td>specifies all ancestors (such as parent, or grandparent) of the current node<\/td>\n<\/tr>\n<tr>\n<td>ancestor-or-self<\/td>\n<td>specifies all ancestors of the current node and the current node itself<\/td>\n<\/tr>\n<tr>\n<td>attribute<\/td>\n<td>specifies all attributes of the current node<\/td>\n<\/tr>\n<tr>\n<td>child<\/td>\n<td>specifies all children of the current node<\/td>\n<\/tr>\n<tr>\n<td>descendant<\/td>\n<td>specifies all descendants (such as children, or grandchildren) of the current node<\/td>\n<\/tr>\n<tr>\n<td>descendant-or-self<\/td>\n<td>specifies all descendants of the current node and the current node itself<\/td>\n<\/tr>\n<tr>\n<td>following<\/td>\n<td>specifies everything in the document after the closing tag of the current node<\/td>\n<\/tr>\n<tr>\n<td>following-sibling<\/td>\n<td>specifies all siblings after the current node<\/td>\n<\/tr>\n<tr>\n<td>namespace<\/td>\n<td>specifies all namespace nodes of the current node<\/td>\n<\/tr>\n<tr>\n<td>parent<\/td>\n<td>specifies the parent of the current node<\/td>\n<\/tr>\n<tr>\n<td>preceding<\/td>\n<td>specifies all nodes that appear before the current node in the document except ancestors, attribute nodes and namespace nodes<\/td>\n<\/tr>\n<tr>\n<td>preceding-sibling<\/td>\n<td>specifies all siblings before the current node<\/td>\n<\/tr>\n<tr>\n<td>self<\/td>\n<td>specifies the current node<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h4>Operators<\/h4>\n<table>\n<tbody>\n<tr>\n<td>Node Set Operator<\/td>\n<\/tr>\n<tr>\n<td>|<\/td>\n<td>Union of two node-sets (CAUTION: The Union operator ANDs two node sets.<br \/>\nIn most computer languages \u2018|&#8217; is an OR operation<\/td>\n<\/tr>\n<tr>\n<td>Arithmetic Operators<\/td>\n<\/tr>\n<tr>\n<td>+<\/td>\n<td>Addition<\/td>\n<\/tr>\n<tr>\n<td>&#8211;<\/td>\n<td>Subtraction<\/td>\n<\/tr>\n<tr>\n<td>*<\/td>\n<td>Multiplication<\/td>\n<\/tr>\n<tr>\n<td>div<\/td>\n<td>Integer Division<\/td>\n<\/tr>\n<tr>\n<td>mod<\/td>\n<td>Modulus (division remainder)<\/td>\n<\/tr>\n<tr>\n<td>Logical Operators<\/td>\n<\/tr>\n<tr>\n<td>and<\/td>\n<td>And<\/td>\n<\/tr>\n<tr>\n<td>or<\/td>\n<td>Or<\/td>\n<\/tr>\n<tr>\n<td>=<\/td>\n<td>Equal<\/td>\n<\/tr>\n<tr>\n<td>!=<\/td>\n<td>Not equal<\/td>\n<\/tr>\n<tr>\n<td>&lt;<\/td>\n<td>Less than<\/td>\n<\/tr>\n<tr>\n<td>&gt;<\/td>\n<td>Greater than<\/td>\n<\/tr>\n<tr>\n<td>&gt;=<\/td>\n<td>Greater than or equal to<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h4>Functions<\/h4>\n<p>There is a vast array of XPath functions. In fact far too many to go into any detail here. If a function requires a text argument, as opposed to a Node orf NodeList, use the text() function to retrieve text associated with the current Node.<\/p>\n<p>For information concerning XPath functions consult Section 4 of the XPath Specification:<\/p>\n<ul>\n<li><a href=\"https:\/\/www.w3.org\/TR\/xpath\/\" target=\"_blank\">https:\/\/www.w3.org\/TR\/xpath\/<\/a><\/li>\n<\/ul>\n<h3>3.3 XPath Expression Examples<\/h3>\n<p>Use the sample XPath expressions below, with the inventory.xml file and the XPath Expression Explorer. Then download for this article includes both the inventory.xml file and the source for the XPath Expression Explorer.<\/p>\n<ul>\n<li>Get a list of all \u201cAMD\u201d processors<br \/>\n\/inventory\/vendor\/computer\/cpu[contains(text(),&#8221;AMD&#8221;)]<\/li>\n<li>Get list of the models of all computers with AMD processors<br \/>\n\/inventory\/vendor\/computer\/cpu[contains(text(),&#8221;AMD&#8221;)]\/preceding-sibling::model<\/li>\n<li>Get all of the computers with cpu of &#8220;Intel Pentium&#8221;<br \/>\n\/inventory\/vendor\/computer\/cpu[text() = &#8220;Intel Pentium&#8221;]<\/li>\n<li>Select all computers with 4 GB ram<br \/>\n\/inventory\/vendor\/computer\/ram[text()=&#8221;4GB&#8221;]<\/li>\n<li>Get all the vendors with computers with AMD processors<br \/>\n\/\/computer[contains(cpu,&#8217;AMD&#8217;)]\/parent::node()\/@name<\/li>\n<\/ul>\n<h2>4. Download The Source Code<\/h2>\n<p>This was a Java Xpath example.<\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code for this article here: <a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/12\/JavaXPathExamples.zip\"><strong>JavaXPathExamples.zip<\/strong><br \/>\n<\/a><\/div>\n","protected":false},"excerpt":{"rendered":"<p>1. Introduction The previous article, Java XPath Best Practices Tutorial (https:\/\/examples.javacodegeeks.com\/core-java\/xpath-best-practices-tutorial\/), explored how to set up a Java application to create a DOM (Document Object Model) document using a DOM parser to read an XML file; and an XPath object to evaluate XPath expressions as applied to the DOM. This article dives into how to &hellip;<\/p>\n","protected":false},"author":107,"featured_media":1204,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[75],"tags":[],"class_list":["post-42673","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-xpath"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Java XPath Examples - Java Code Geeks<\/title>\n<meta name=\"description\" content=\"This article delves into how to construct XPath expressions. Starting with the syntax and ending with some examples to sum up the concepts explored.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Java XPath Examples - Java Code Geeks\" \/>\n<meta property=\"og:description\" content=\"This article delves into how to construct XPath expressions. Starting with the syntax and ending with some examples to sum up the concepts explored.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/\" \/>\n<meta property=\"og:site_name\" content=\"Examples Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:published_time\" content=\"2016-12-26T09:00:35+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"David Guinivere\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"David Guinivere\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"10 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/\"},\"author\":{\"name\":\"David Guinivere\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/6b72a73c5929404de88a306c107735ed\"},\"headline\":\"Java XPath Examples\",\"datePublished\":\"2016-12-26T09:00:35+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/\"},\"wordCount\":1072,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"articleSection\":[\"XPath\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/\",\"name\":\"Java XPath Examples - Java Code Geeks\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"datePublished\":\"2016-12-26T09:00:35+00:00\",\"description\":\"This article delves into how to construct XPath expressions. Starting with the syntax and ending with some examples to sum up the concepts explored.\",\"breadcrumb\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/#primaryimage\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"width\":150,\"height\":150,\"caption\":\"Bipartite Graph\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/examples.javacodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java Development\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Core Java\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"xml\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/xml\/\"},{\"@type\":\"ListItem\",\"position\":5,\"name\":\"XPath\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/xml\/xpath\/\"},{\"@type\":\"ListItem\",\"position\":6,\"name\":\"Java XPath Examples\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Examples and Code Snippets\",\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/javacodegeeks\",\"https:\/\/x.com\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/6b72a73c5929404de88a306c107735ed\",\"name\":\"David Guinivere\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/11\/David-Guinivere-96x96.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/11\/David-Guinivere-96x96.jpg\",\"caption\":\"David Guinivere\"},\"description\":\"David graduated from University of California, Santa Cruz with a Bachelor\u2019s degree in Information Science. He has been actively working with Java since the days of J2SE 1.2 in 1998. His work has largely involved integrating Java and SQL. He has worked on a wide range of projects including e-commerce, CRM, Molecular Diagnostic, and Video applications. As a freelance developer he is actively studying Big Data, Cloud and Web Development.\",\"sameAs\":[\"https:\/\/www.javacodegeeks.com\",\"http:\/\/www.linkedin.com\/in\/davidguinivere\"],\"url\":\"https:\/\/examples.javacodegeeks.com\/author\/david-guinivere\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Java XPath Examples - Java Code Geeks","description":"This article delves into how to construct XPath expressions. Starting with the syntax and ending with some examples to sum up the concepts explored.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/","og_locale":"en_US","og_type":"article","og_title":"Java XPath Examples - Java Code Geeks","og_description":"This article delves into how to construct XPath expressions. Starting with the syntax and ending with some examples to sum up the concepts explored.","og_url":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/","og_site_name":"Examples Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_published_time":"2016-12-26T09:00:35+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","type":"image\/jpeg"}],"author":"David Guinivere","twitter_card":"summary_large_image","twitter_creator":"@javacodegeeks","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"David Guinivere","Est. reading time":"10 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/#article","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/"},"author":{"name":"David Guinivere","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/6b72a73c5929404de88a306c107735ed"},"headline":"Java XPath Examples","datePublished":"2016-12-26T09:00:35+00:00","mainEntityOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/"},"wordCount":1072,"commentCount":0,"publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","articleSection":["XPath"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/","url":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/","name":"Java XPath Examples - Java Code Geeks","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/#primaryimage"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","datePublished":"2016-12-26T09:00:35+00:00","description":"This article delves into how to construct XPath expressions. Starting with the syntax and ending with some examples to sum up the concepts explored.","breadcrumb":{"@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/#primaryimage","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/xml\/xpath\/java-xpath-examples\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/examples.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"},{"@type":"ListItem","position":4,"name":"xml","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/xml\/"},{"@type":"ListItem","position":5,"name":"XPath","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/xml\/xpath\/"},{"@type":"ListItem","position":6,"name":"Java XPath Examples"}]},{"@type":"WebSite","@id":"https:\/\/examples.javacodegeeks.com\/#website","url":"https:\/\/examples.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/examples.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/examples.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/6b72a73c5929404de88a306c107735ed","name":"David Guinivere","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/11\/David-Guinivere-96x96.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2016\/11\/David-Guinivere-96x96.jpg","caption":"David Guinivere"},"description":"David graduated from University of California, Santa Cruz with a Bachelor\u2019s degree in Information Science. He has been actively working with Java since the days of J2SE 1.2 in 1998. His work has largely involved integrating Java and SQL. He has worked on a wide range of projects including e-commerce, CRM, Molecular Diagnostic, and Video applications. As a freelance developer he is actively studying Big Data, Cloud and Web Development.","sameAs":["https:\/\/www.javacodegeeks.com","http:\/\/www.linkedin.com\/in\/davidguinivere"],"url":"https:\/\/examples.javacodegeeks.com\/author\/david-guinivere\/"}]}},"_links":{"self":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/42673","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/users\/107"}],"replies":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=42673"}],"version-history":[{"count":0,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/42673\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media\/1204"}],"wp:attachment":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=42673"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=42673"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=42673"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}