Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XPath to select Element by attribute value

Tags:

xml

xpath

People also ask

What is XPath by attribute?

Definition of XPath attribute. For finding an XPath node in an XML document, use the XPath Attribute expression location path. We can use XPath to generate attribute expressions to locate nodes in an XML document.

What will be the XPath expression to select?

XPath uses path expressions to select nodes or node-sets in an XML document. The node is selected by following a path or steps.


You need to remove the / before the [. Predicates (the parts in [ ]) shouldn't have slashes immediately before them. Also, to select the Employee element itself, you should leave off the /text() at the end or otherwise you'd just be selecting the whitespace text values immediately under the Employee element.

//Employee[@id='4']

Edit: As Jens points out in the comments, // 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 full path, for example:

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

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

//*[@id='4']

Try doing this :

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