E4X:分配给根节点
我在这里使用 Adobe Flex/Air,但据我所知这适用于所有 JavaScript。 我已经遇到过这个问题好几次了,一定有一个简单的解决方案!
假设我有以下 XML(使用 e4x):
var xml:XML = <root><example>foo</example></root>
我可以使用以下代码更改示例节点的内容:
xml.example = "bar";
但是,如果我有以下内容:
var xml:XML = <root>foo</root>
如何更改根节点的内容?
xml = "bar";
显然这不起作用,因为我试图将字符串分配给 XML 对象。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您尝试更改文档的根元素,则实际上并不需要 - 只需丢弃现有文档并替换它即可。 或者,只需将您的元素包装在更合适的根元素中(无论如何您都不应该编辑根节点),然后就可以了。
当然,这并不能回答你的问题。 有一个丑陋的 JS hack 可以做你想做的事,但请记住,它可能比执行上述操作慢得多。 无论如何,这里是:
您可以忽略 fix_syntax_highlighter 注释。
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:
You can ignore the fix_syntax_highlighter comment.
啊,谢谢西奥 - 确实,我似乎很困惑。 我认为混乱的根源来自于我能够分配的事实
,我现在猜测只是隐式调用 XML.toString() 来转换 XML->String。 setChildren() 就是我一直在寻找的。
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
Which I now guess is just implicity calling XML.toString() to convert XML->String. setChildren() is what I was looking for.
看来您将变量与它们包含的值混淆了。 赋值
会更改 变量
node
指向的值,但不会更改node
当前指向的对象。 要执行您想做的操作,您可以使用XML
类的setChildren
方法:It seems you confuse variables for the values they contain. The assignment
changes the value the variable
node
points to, it doesn't change anything with the object thatnode
currently points to. To do what you want to do you can use thesetChildren
method of theXML
class: