E4X : Assigning to root node
-
09-06-2019 - |
Question
I am using Adobe Flex/Air here, but as far as I know this applies to all of JavaScript. I have come across this problem a few times, and there must be an easy solution out there!
Suppose I have the following XML (using e4x):
var xml:XML = <root><example>foo</example></root>
I can change the contents of the example node using the following code:
xml.example = "bar";
However, if I have this:
var xml:XML = <root>foo</root>
How do i change the contents of the root node?
xml = "bar";
Obviously doesn't work as I'm attempting to assign a string to an XML object.
Solution
It seems you confuse variables for the values they contain. The assignment
node = textInput.text;
changes the value the variable node
points to, it doesn't change anything with the object that node
currently points to. To do what you want to do you can use the setChildren
method of the XML
class:
node.setChildren(textInput.text)
OTHER TIPS
Ah thank you Theo - indeed seems I was confused there. I think the root of the confustion came from the fact I was able to assign
textInput.text = node;
Which I now guess is just implicity calling XML.toString() to convert XML->String. setChildren() is what I was looking for.
If you're trying to change the root element of a document, you don't really need to-- just throw out the existing document and replace it. Alternatively, just wrap your element in a more proper root element (you shouldn't be editing the root node anyway) and you'd be set.
Of course, that doesn't answer your question. There's an ugly JS hack that can do what you want, but bear in mind that it's likely far slower than doing the above. Anyway, here it is:
var xml = <root>foo</root>; // </fix_syntax_highlighter>
var parser = new DOMParser();
var serializer = new XMLSerializer();
// Parse xml as DOM document
// Must inject "<root></root>" wrapper because
// E4X's toString() method doesn't give it to us
// Not sure if this is expected behaviour.. doesn't seem so to me.
var xmlDoc = parser.parseFromString("<root>" +
xml.toString() + "</root>", "text/xml");
// Make the change
xmlDoc.documentElement.firstChild.nodeValue = "CHANGED";
// Serialize back to string and then to E4X XML()
xml = new XML(serializer.serializeToString(xmlDoc));
You can ignore the fix_syntax_highlighter comment.