문제

In the following code block if I debug the and look at the var obj.theID it shows as an XMLList. Even though the code traces properly I feel it should be a string not an XMLList.

So my question is how can I get it to assign a string and not an XMLList?

var myXML:XML = new XML(
<panels>
  <panel id="1"/>
  <panel id="2"/>
  <panel id="3"/>
</panels>
);

var panels:XMLList = new XMLList( myXML.children());

trace( panels.length()); // is as expected
for each( var panel:XML in (new XMLList( myXML.children())) ){
    var obj:Object = new Object( );

    // XMLList is assigned here but why? and how can I make it a string?
    obj.theID = panel.@id;

    // id is traced as expected but apparently it is just converting the XMLlist to a string.
    trace( panel.@id)
}
도움이 되었습니까?

해결책

The AS3 xml parser simply reads any native xml content, either attribute or node data as a string, and can be used as such without type conversion. Which is one of things that makes xml so convenient in flash. But if you check the type, it will return as XML unless you specifically cast it (which is essentially what toString() does).

    for each( var panel:XML in panels ){
    var obj:Object = new Object( );

    obj.theID = panel.@id;

    // the native type is xml, tho can be read without conversion as a string 
    trace( typeof obj.theID) // type:xml
    trace( typeof panel.@id) // type:xml

    // simply cast it to string
    obj.theIDString = String(panel.@id); 
    trace( typeof obj.theIDString) // type:string
}

-- update --

Of note = XML and XMLlist can be and often are used interchangeably. They each have access to a similar set of methods, but there is an important difference. XML may have exactly one root node, while XMLlist may have several. This may not make much of a difference in normal usage, but depending on the structure of your incoming xml, may be a critical distinction. Normally, I just use the XML type. Here is a good article on xml vs xmllist.

Cheers

다른 팁

Use toString() to get the value.

Example:

var xml:XML = <thing>hello</thing>;

trace(xml.toString()) //hello

Your new code:

var myXML:XML =
<panels>
    <panel id="1" />
    <panel id="2" />
    <panel id="3" />
</panels>;

var panels:XMLList = myXML.children();

var panel:XML;
for each(panel in panels)
{
    var obj:Object =
    {
        stringID: panel.@id.toString(),
        normalID: panel.@id
    };

    trace(typeof(obj.stringID), obj.stringID); //string
    trace(typeof(obj.normalID), obj.normalID); //xml
}

This is part of the E4X Parser that ActionScript uses.

The child nodes of an XML element are always wrapped in an XMLList. Even if the an element has only one child or attributes.

Easiest way to get a string on your object is use

var obj:Object = new Object( ); obj.theID = panel.@id.toString();

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top