tags:

views:

820

answers:

1

Consider this scenario:

Using Javascript/E4X, in a non-browser usage scenario (a Javascript HL7 integration engine), there is a variable holding an XML snippet that could have multiple repeating nodes.

<pets>       
 <pet type="dog">Barney</pet>
 <pet type="cat">Socks</pet>
</pets>

Code:

var petsXml; // pretend it holds the above xml value
//var cat = petsXml['pet']..... ?

Question: using E4X, how can you select the correct pet node with the type attribute holding the value of string 'cat'?

Update:

Some learnings with E4X:

  • to select a single/first node by an attribute value: var dog = petsXml.(@type == "dog");
  • to get a value from one node's specific attribute: var petType = somePetNode.@type;
+2  A: 
var petsXml;
var catList = petsXml.*.(@type == "cat");

See "Filters" here or "parameterized locate" over here.

pianoman
thanks Pianoman. That worked fine. Although I've successfully implemented the solution as petsXml.(@type == "cat"); Is the asterisk indicating that multiples would be returned, whereas without would be the first match found?
p.campbell
You are absolutely right. The `*` should scan all the `<pet>` nodes, and `catList` could very well be an array if there are >1 cats.
pianoman