danielovich
danielovich

Reputation: 9687

get attribute from selectNodes in JavaScript and XML?

I am trying to get an attribute from an XML node from JavaScript.

item.selectNodes("enclosure[@url]")

That is not working like I thought it would :(

Any hints ?

thanks!

Upvotes: 1

Views: 1957

Answers (2)

Chris Nielsen
Chris Nielsen

Reputation: 14758

This:

item.selectNodes("enclosure[@url]")

will give you a collection of enclosure nodes that have a url attribute.

To get a collection of url attribute nodes that are on enclosure nodes, do this:

item.selectNodes("enclosure/@url")

Which you must then loop over to get the values of each one. Remember this gives you attribute nodes, not attribute values. You can use attributeNode.nodeValue to get the value from the node.

If you are expecting just one such node, then use selectSingleNode instead of selectNodes. This will give you the first matching node, instead of a collection of all matching nodes.

Upvotes: 2

Ghislain Fourny
Ghislain Fourny

Reputation: 7279

[@url]

is a predicate, which does not select the attribute but filters the "enclosure" nodes that do have a url attribute.

In XPath,

enclosure/@url

would select the attribute.

Upvotes: 5

Related Questions