In the previous section of XPath tutorial we have studied how to show all elements of an XML file. In this section we are describing you the use of @ for attribute in the XPath query. The "@" selects attribute.
In this example we have created an XML file "person.xml" as in our previous section, which is necessary to execute XPath query on to it. This "persons.xml" contains information related to name, age, gender of different persons.
Here is the full source code for persons.xml file as follows :
Now we have declared a class XPathAttribute and in this class we are parsing the XML file with JAXP. First of all we need to load the document into DOM Document object. We have put that persons.xml file in that current working directory.
Above lines of code parses "persons.xml" file and creates a Document object. Next we have created XPath object with the use of XPathFactory.
We want to show all elements with attribute id="3" of the person so we can write this in the XPath query as :
"//person[@id='3']/*" -it will fetch
all elements with person id="3" .
Full example code is given as below:
To run this example :
output would be like this:
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.