0

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)

1 Answer 1

3

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");
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, your answer answered my question, that I had formulated in a wrong way. I have edited the question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.