Reputation: 1294
I have loaded an external XML and stored it in a variable. Now I have another string variable (dynamic) which contains path to a specific node. I need to find the value of the node according to the path in variable.
External XML Loaded: rss.cnn.com/rss/edition.rss (No proxy problem, its being loaded in var. I have checked by tracing the var)
private function feedLoad(e:Event):void {
feedXml = new XML(e.target.data);
feedRef = "channel.title"; // (This is actually dynamic value, and can go n-level deep)
title_txt.text = feedXml[feedRef];
}
How to reference the child path according to the variable? I have tried:
feedXml[feedRef]
feedXml.feedRef
But its not working.
Upvotes: 0
Views: 51
Reputation: 18747
You should split your string by dots with var feedArr:Array = feedRef.split(".")
, then iterate through your resultant array down with xml[feedArr[i]]
which is not an XML
but XMLList
(or null), then get each child in order and get next property, and so on. An example, that assumes there is only one requested output ever:
var xml:XML = new XML("<foo a=\"X\"><moo b=\"Y\">Moo</moo><bar c=\"Z\"><baz>Meow</baz></bar></foo>");
var foo:XMLList;
var x:XML;
var s:String = "foo.bar.baz";
var a:Array = s.split(".");
var d:XML = xml;
for (var i:int = 0; i < a.length; i++) {
if (d) {
foo = d[a[i]];
for each (x in foo) d = x;
// here it's best to recurse into X instead of using only last X
}
}
if (d) trace("d",d.toXMLString());
Upvotes: 1
Reputation: 5478
I think what you're looking for is:
feedXML.child(feedRef);
If you want all the nodes called "title", then you can do a recursive function:
function searchXML(xml:*):void {
var xmlList:XMLList = xml.children();
if (xmlList.length>0) {
for each (var xmlItem in xmlList) {
searchXML(xmlItem);
}
if (xml.name() == "title") {
trace(xml.text());
}
}
Sorry if any errors, I have no way to test this right now.
More about traversing an XML in Actionscript 3 here: Traversing XML structures
Upvotes: 1