'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 1:[1]

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"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1