Javascript E4X: Select a node based on an attribute value

e4xjavascript

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;

Best Answer

var petsXml;
var catList = petsXml.*.(@type == "cat");

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