E4X/AS3, get an array of text elements without looping

无人久伴 提交于 2020-01-06 13:51:11

问题


this is part of an XML file I retrieve using AS3 E4X:

<links>
    <link>
      <label>Versions</label>
      <href>http://mylink1</href>
    </link>
    <link>
      <label>Configurations</label>
      <href>http://myLink2</href>
    </link>
</links>

I want to retrieve the values of labels, so I write:

document.links.link.label.text();

This returns VersionsConfigurations. I need this as Array ([Versions, Configurations]) but I would like not to use a loop. Is there any other way?


回答1:


Well, this is a "don't try this at home" solution, but here you are. :)

You can use E4X search expression to do whatever you want to nodes of an XMLList.

This works as follows: someXMLList.(expression), where expression is any AS3 code that can access each node's properties and methods with no need of qualifying their names. For instance, you could do the following:

yourXML.descendants("label").(trace("label text: ", text()));

Note that I'm using text() here with no access . operations. Actually this will return an new XMLList for all nodes, where expression evaluated to true. Since trace() returns void, the resulting list will be empty. Internally there is of course a loop through all nodes of XMLLIst that is created by calling descendants() (or using .. operator).

You can construct your array the same way.

var doc:XML = 
<links>
    <link>
      <label>Versions</label>
      <href>http://mylink1</href>
    </link>
    <link>
      <label>Configurations</label>
      <href>http://myLink2</href>
    </link>
    <link>
      <label>A label
with
multiple
line 
breaks</label>
      <href>http://myLink3</href>
    </link>
</links>;

trace(doc.descendants("label").text().toXMLString().split("\n"));
/* Trace output (incorrect):
Versions,Configurations,A label
,with
,multiple
,line 
,breaks
*/

var list:Array = [];
doc.descendants("label").(list.push(text().toString()));
trace(list);
/* Trace output (correct):
Versions,Configurations,A label

with

multiple

line 

breaks
*/

That may be useful when performing some complicated searches on an XMLList. However in your case I think you should instead use simple splitting of a string representation or a regular expression as Shane suggests.




回答2:


An alternative technique could be to use a regular expression, although this particular example is dependent on your labels always starting with a capital and otherwise containing only lower case characters.

var regex:RegExp = /[A-Z][a-z]+/g;
var inString:String = "VersionsConfigurations";
var outArray:Array = inString.match(regex);
trace(outArray.length); // 2


来源:https://stackoverflow.com/questions/6813584/e4x-as3-get-an-array-of-text-elements-without-looping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!