繁体   English   中英

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

[英]How to get XML tag names in AS3

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

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

我将文件加载到ArrayCollection中,并可以按名称访问我需要的每个项目,例如[“ City”] //返回纽约

我想做的就是获取标记名称(例如State或Zip而不是NY或10098),而不是获取值。

在处理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 ]);
}

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

就像是:

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

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

每个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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM