Search code examples
xmlxpathxqueryxpath-2.0xpath-1.0

How to get attribute value of parent tag by passing child tag value in Xpath


<?xml version="1.0" encoding="UTF-8"?>
<category tid="titleId">
      <key>titlekey</key>
      <category-abbreviation/>
      <title>main title </title>
    </category>

For example, say for above document I need value of tid that is "titleId" and to fetch it I have input key=titlekey. Let me know how to find attribute value tid using xpath expression. documents can have multiple category nodes.


Solution

  • You can use XPath expression like this:
    Locate the parent category node based on it's child element key value and then get the tid attribute value from that parent node.

    "//category[./key[text()='titlekey']]/@tid"
    

    You can also use this expression as well:

    "//category[key='titlekey']/@tid"