问题
Consider this XML snippet with "nodes" which can have unlimited child levels of "subnode" elements.
I want to find @type
attribute of the node
for any given subnode
, based on its @id
attribute. For example, if I have an id of 9 then I want to return the type="foo" from above.
<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>
The E4X I have come up with, but which fails is:
xml.node.(subnode.(@id == '8')).@type
I can kind of see why it doesn't work. What would make more sense is the following but the syntax fails (in AS3):
xml.node.(..subnode.(@id == '8')).@type
How can this be done?
回答1:
You should be able to get the type value using this E4X:
xml.node.(descendants("subnode").@id.contains("8")).@type;
回答2:
Try this
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)
回答3:
Having given up on E4X I used a "hack" and did it in ActionScript instead. 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"
Seems a mess though. Would still be interested in any plain E4X solution.
来源:https://stackoverflow.com/questions/1427810/can-e4x-get-attribute-of-a-parent-node-based-on-attribute-of-a-child-at-any-leve