user1960836
user1960836

Reputation: 1782

Getting an element that has specific attribute

My XML looks like this

<Data>
  <a Messages="1">
  <b Messages="2" Labelvisibility="yes">
  <c Messages="3">
</Data>

I want to select the element that has an attribute named Labelvisibility. There will only be one such element at a time.

My attempt was: (assuming that "a" is the XML file above)

var b = a.selectSingleNode("//Messages[@Labelvisibility]");

According to w3schools, this expression: //title[@lang] selects all the title elements that have an attribute named lang

So I am trying to get the element that has an attribute name Labelvisibility by following this example, but my code returns null. What am I doing wrong? If there is an esier/smarter way than the one from w3schools, please share.

Thanks

-------------------------------Update-------------------------------------.....

I see that I wasn't clear and precise in my question. What I want it to return is: `Messages="Another"

In another case I want it only to return the attribute value`. If I do this:

a.selectSingleMode("//@Messages")

it will print Messages="1"

How can I say print the attribute value of "Message" where there is a Labelvisibility attribute?

So that it will print 2 (Since the value 2 is where there is a labelvisibility)

Upvotes: 0

Views: 46

Answers (1)

Rudolf Yurgenson
Rudolf Yurgenson

Reputation: 603

You don't have Messages element in your XML, that's why result is null.

Fixed version:

var b = a.selectSingleNode("//*[@Messages][@Labelvisibility]");

I.e. all elements that contain both Messages and Labelvisibility attributes. If check for Messages attribute is surplus, then you can simply remove this predicate.


a.selectSingleMode("//@Messages") it will print Messages="1"

This happens because //@Messages returns three attribute nodes and 1 is the first one according to document order.

How can I say print the attribute value of "Message" where there is a Labelvisibility attribute?

So that it will print 2 (Since the value 2 is where there is a labelvisibility)

var b = a.selectSingleNode("//*[@Labelvisibility]/@Messages");

Upvotes: 3

Related Questions