Can the E4X get the Node parent attribute based on the child attribute at any level?

Consider this XML snippet with β€œnodes”, which can have unlimited levels of subnode children.

I want to find the @type node attribute for any given subnode based on its @id attribute. For example, if I have identifier 9, then I want to return type = "foo" on top.

 <xml> <node type="bar"> <subnode id="4"> <subnode id="5"/> </subnode> <subnode id="6"/> </node> <node type="foo"> <subnode id="7"> <subnode id="8"> <subnode id="9"/> </subnode> </subnode> <subnode id="10"/> </node> </xml> 

E4X, which I came across, but which does not work:

 xml.node.(subnode.(@id == '8')) .@type 

I can understand why this is not working. What would be more reasonable is the following, but the syntax will not work (in AS3):

 xml.node.(..subnode.(@id == '8')) .@type 

How can I do that?

+4
source share
3 answers

You can get the type value using this E4X:

 xml.node.(descendants("subnode") .@id.contains ("8")) .@type ; 
+5
source

Having abandoned E4X, I used the hack and did it in ActionScript. Here's how:

 var p:XML = xml..subnode.(attribute('id').toLowerCase() === "8")[0]; //Traverse back up to the parent "node" while ( p.name().toString() === "subnode" ) { p = p.parent(); } Alert.show( p.@type ); //Should say "foo" 

It seems a mess. Anyway, he will be interested in any simple E4X solution.

0
source

try it

 for each(var node:XML in xml.node) { var subnodes:XMLList = node..subnode; if(subnodes.(@id == '9').length() != 0) return node.@type ; } 

EDIT: Even this should work:

 if(node..subnode.(@id == '9').length() != 0) 
0
source

All Articles