问题
I have an XML document:
var xml:XML = new XML(<rootNode>
<head>
<meta name="template" content="Default" />
</head>
<mainSection>
<itemList>
<item>
<video src={this.videoURL} />
<img src={this.src}></img>
</item>
</itemList>
</mainSection>
</rootNode>);
What I'd like to do, is when certain conditions are me, insert another at the beginning of itemList.
var newNode:XMLList = new XMLList("<item><video src=\"" + _videoSource + "\"></video></item>");
I'm able to generate and trace newNode just fine, but whenever I try to add it using insertChildBefore, it always returns undefined.
var contentNode:XML = new XML(xml.mainSection.itemList.item);
xml.insertChildBefore(contentNode ,newNode)
contentNode always traces fine, but it always fails when trying insertChildBefore or insertChildAfter. The weird thing is, if I make contentNode less specific (like xml.mainSection) then it works as expected.
Thanks for any help, this is driving me insane!
回答1:
There are two problems here (I've now tested this code - it should work for you):
The variable
xmlis not the direct parent of theitemnode you are inserting. You're callinginsertChildBeforeon thexmlnode, but yourcontentNodeis not its direct child.The
contentNodevariable you're trying to insert ahead of is a copy of the node you want; you shouldn't be creating a brand new XML object.
Try this instead:
var contentNode:XML = xml.mainSection.itemList.item[0];
var parentNode:XML = xml.mainSection.itemList[0];
parentNode.insertChildBefore( contentNode, newNode[0] );
来源:https://stackoverflow.com/questions/189033/having-trouble-with-insertchildbefore-and-insertchildafter-in-as3