Gowtham
Gowtham

Reputation: 941

How to add Attribute to XMLLIST without looping in E4X

I have the following xml

var xml:XML = <test>
    <node id='1'/>
    <node id='2'/>
    <node id='3'/>
    <node id='4'/>
    <node id='5'/>
</test>;

var xmlist:XMLList = xml.children();

for each (var node:XML in xmlist) 
{
    node.@newAttribute = "1";
}

I'm looping through each node and adding an attribute. How can I do this without looping? I've tried this

xmlist.attributes().@newAttrib = "1";

but I'm getting the error "TypeError: Error #1089: Assignment to lists with more than one item is not supported."

Upvotes: 4

Views: 866

Answers (2)

Ozan Deniz
Ozan Deniz

Reputation: 135

it's been 2 weeks since this question is asked but there will always be more people in need of help.

TypeError: Error #1089 is caused by result of more than one objects in xml.

Normally I took this error by something like this operation= xml.classes.(@id==1).students.(@no==2).@Grade="A"; The error caused because there were more than one students in the xml.classes, so it tried to return all of them. As the error says : "Assignment to lists with more than one item is not supported." You cannot assign a value to more than one object at the same time.

And since you add all the s into the XMLList, I'm not sure of the reason since I don't use XMLList. it's a useless as I think. So if you change your code as

var xml:XML = <test>
    <node id='1'/>
    <node id='2'/>
    <node id='3'/>
    <node id='4'/>
    <node id='5'/>
</test>;


for each (var n:XML in xml) 
{
    n.@newAttribute = "1";
}

The problem should be solved. But I would suggest you to use "id" as a unique key. Then you can use that unique key to reach specific items in the XML, like

xml.node.(@id=="1").@newAttribute="1";

I hope this helps you. Take care

-Ozan

Upvotes: 1

Sunil D.
Sunil D.

Reputation: 18193

As the error says, it's not supported. Since you cannot do this assignment to multiple elements, I don't see a way to do this without iterating over the xml.

For fun, I tried this and got the same error: xml.node.@newAttribute=1

It's just a slightly more terse version of:

var xmlist:XMLList = xml.children();
xmlist.attributes().@newAttrib = "1";

Upvotes: 0

Related Questions