17

I have a simple requirement where in I need to fetch the value of attribute xml:id i.e af1. I am making use of a SAXParser and here is my xpath:a/aff/@xml:id on the contrary I was able to fetch value of using the xpath:a/aff/@value.

But i was unable to retrieve the value could you please help me?

<?xml version="1.0" encoding="UTF-8" ?>
<a>
   <aff xml:id="af1" value="a">
        <uAff>
            Hello
        </uAff>
    </aff>
    <aff xml:id="corr1">
        <uAff>
            Hello1
        </uAff>
    </aff>
</a>

Thanks in advance.

Yurets
  • 3,999
  • 17
  • 54
  • 74
KRISHNA JAYANTH
  • 233
  • 3
  • 11

2 Answers2

27

To get the value of the attributes you could use:

/a/aff/@*[name()='xml:id']
tibtof
  • 7,857
  • 1
  • 32
  • 49
  • Thanks a lot :-) Your answer was SPOT ON :-) Can u please tell how to get value of the tag which has colon.Say instead of aff if it was aff:a, how can we parse it? – KRISHNA JAYANTH Jun 05 '12 at 10:02
  • if you have aff:a then aff must be a namespace, and that is a different problem. have a look here: http://stackoverflow.com/questions/536441/xpath-namespace-driving-me-crazy – tibtof Jun 05 '12 at 10:10
  • 1
    or you can use local-name() instead of name(), FWIW http://stackoverflow.com/a/11131700/32453 – rogerdpack Sep 08 '14 at 22:44
  • I am not an expert on xpath but it seems if you reach an attribute you can always access its parent element by adding a /.. [slash double dot] at the end i.e. : `"//@*[name()='xml:id' and .='corr1']/.."` – Ahmad Nadeem Nov 11 '22 at 07:36
1

/a/aff/@xml:id works just fine in getting the values...

Are you trying to get both values?

If you are trying to get just the first value you could use /a/aff[1]/@xml:id

DRTauli
  • 731
  • 1
  • 8
  • 25
  • 2
    Your answer is correct if there is no colon, but when there is a colon it doesnt fetch the attribute value with /a/aff/@xml:id this xpath. – KRISHNA JAYANTH Jun 05 '12 at 10:06