XPath to select Element by attribute value

XmlXpath

Xml Problem Overview


I have following XML.

<?xml version="1.0" encoding="UTF-8"?>
<Employees>
	<Employee id="3">
		<age>40</age>
		<name>Tom</name>
		<gender>Male</gender>
		<role>Manager</role>
	</Employee>
	<Employee id="4">
		<age>25</age>
		<name>Meghna</name>
		<gender>Female</gender>
		<role>Manager</role>
	</Employee>
</Employees>

I want to select Employee element with id="4".

I am using below XPath expression which is not returning anything.

//Employee/[@id='4']/text()

I checked it at http://chris.photobooks.com/xml/default.htm and it says invalid xpath, not sure where is the issue.

Xml Solutions


Solution 1 - Xml

You need to remove the / before the [. Predicates (the parts in [..]) shouldn't have slashes immediately before them - they go directly after the node selector they are associated with.

Also, to select the Employee element itself, you should leave off the /text() at the end. Otherwise you'd just be selecting the whitespace text values immediately under the Employee element.

//Employee[@id = '4']

One more thing to note: // can be very slow because it searches the entire document for matching nodes. If the structure of the documents you're working with is going to be consistent, you are probably best off using a more explicit path, for example:

/Employees/Employee[@id = '4']

Solution 2 - Xml

As a follow on, you could select "all nodes with a particular attribute" like this:

//*[@id='4']

Solution 3 - Xml

Try doing this :

/Employees/Employee[@id=4]/*/text()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPankajView Question on Stackoverflow
Solution 1 - XmlJLRisheView Answer on Stackoverflow
Solution 2 - XmlrogerdpackView Answer on Stackoverflow
Solution 3 - XmlGilles QuenotView Answer on Stackoverflow