如何在AS3中获取XML标记名称

时间:2009-11-10 20:34:12

标签: xml flex actionscript-3

我正在尝试在我的AS3程序中获取子XML标记名称。例如,我有一个包含以下信息的文件:

<LocationInfo>
   <City>New York City</City>
   <State>NY</State>
   <Zip>10098</Zip>
</LocationInfo>

我将文件加载到ArrayCollection中,并且可以通过名称访问我需要的每个项目     [“城市”] //返回纽约

我想要做的是获取标签名称,例如State或Zip而不是NY或10098,而不是获取值。

3 个答案:

答案 0 :(得分:3)

在处理XML时,使用XMLListCollection几乎总是更好。在大多数情况下,您根本不需要ArrayCollection的附加功能,XMLListCollection肯定会让事情变得更容易。此外,ArrayCollections并不总是正确地序列化事物。我不能给你一个特定的情况,但我知道我不得不重构,因为XML没有正确存储。最后,XMLListCollection.toXMLString()将为您提供比ArrayCollection.toString更好的数据状态视图。

使用XMLListCollection,您要查找的内容将在以下之一中完成:

var coll:XMLListCollection = <xml-here/>

// Iterate through all of the children nodes
for( var i:int = 0; i < coll.children().length(); i++ )
{
    var currentNode:XML = coll.children()[ i ];
    // Notice the QName class?  It is used with XML.
    // It IS NOT a String, and if you forget to cast them, then
    // currentNode.localName() will NEVER be "city", even though it may
    // trace that way.
    var name:QName      = currentNode.name(); // url.to.namespace::city
    var locName:QName   = currentNode.localName() // City
}

// get all city nodes in the current parent element
var currCities:XMLList = currentParentNode.cities; // currentParentNode can be 
// an XMLList, an XML object, an XMLListAdapter, or an XMLListCollection.
// This means that you can do something like coll.cities.cities, if there are
// children nodes like that.
for( i = 0; i < cities.length(); i++ )
{
    var currentCity:XML = cities[ i ];
}

// get all city nodes in all descendant nodes.
var cities:XMLList = currentParentNode.descendants( 
                         new QName( "url.to.namespace", "City" ) 
                     );
for( i = 0; i < cities.length(); i++ )
{
    var currentCity:XML = cities[ i ];
}

如果你真的必须使用ArrayCollection,那么你可以使用for ... in语法来实现你想要的:

// This is one of the few times I recommend anonymous typing.  When dealing with
// XML (which likely has already been turned into a String anyway, but be safe )
// anonymous syntax can give you better results.

// it = iterant, I use this to contrast with i for my sanity.
for(var it:* in coll) 
{
    trace(it,"=",coll[ it ]);
}

答案 1 :(得分:2)

您可以使用localName属性获取XMLNode的元素名称。

类似的东西:

var xml : XML = <LocationInfo>...</LocationInfo>;

foreach(var child : XMLNode in xml.LocationInfo.childNodes)
{
    trace(child.localName + " = " + child.nodeValue);
}

答案 2 :(得分:0)

每个LocationInfo标记都成为ArrayCollection中的一个条目。每个条目都是一个动态对象,所以你真正要问的是如何从动态对象中获取属性名称。这已经得到了解答,尽管他们以不同的方式提出了这个问题。这是原始页面的链接:

https://stackoverflow.com/questions/372317/how-can-i-get-list-of-properties-in-an-object-in-actionscript

这里的答案似乎最直接:

var obj:Object; // I'm assuming this is your object

for(var id:String in obj) {
  var value:Object = obj[id];

  trace(id + " = " + value);
}