手工构建的 w3c 文档文本节点会导致奇怪的行为
以下代码会导致类似于以下内容的输出:
<parent>
<child/>
<secondChild/> ...
我预计它看起来如下:
<parent>
parent text
<child></child>
<secondChild>second child text</secondChild>
有问题的代码如下:
Element parentNode= document.createElement("parent");
Text textNode = document.createTextNode("parent text");
Element childNode = document.createElement("child");
parentNode.appendChild(childNode);
childNode.appendChild(textNode);
childNode = document.createElement("secondChild");
textNode = document.createTextNode("second child text");
parentNode.appendChild(childNode);
childNode.appendChild(textNode);
我的问题是,通过重新引用 textNode
,我是否遗漏了一些东西构建文档时出现问题?
The following code causes output that resembles the following:
<parent>
<child/>
<secondChild/> ...
I would anticipate it to look as follows:
<parent>
parent text
<child></child>
<secondChild>second child text</secondChild>
The code in question is as follows:
Element parentNode= document.createElement("parent");
Text textNode = document.createTextNode("parent text");
Element childNode = document.createElement("child");
parentNode.appendChild(childNode);
childNode.appendChild(textNode);
childNode = document.createElement("secondChild");
textNode = document.createTextNode("second child text");
parentNode.appendChild(childNode);
childNode.appendChild(textNode);
My question is is there something I am missing by re-referencing the textNode
that causes an issue when building a Document?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它按我的预期工作。也许你打印的方式有问题?试试这个:
输出:
编辑: 如果您确实希望第一个文本位于子级之外而不是子级内部,则需要将代码更改为:
但我假设您刚刚输错了 XML 。
It works as expected for me. Maybe there's a problem with how you're printing it out? Try this:
Output:
Edit: If you really mean that you want the first text outside of the child instead of inside it, you need to change your code to:
but I assumed you had just mistyped the XML.
是的,您不能重用任何节点。在 DOM 中,每个节点都有一个父节点,并且只有一个父节点,一旦附加一个节点(无论是文本节点还是元素),该节点就会被附加,并且如果不首先分离,则不应附加到任何其他父节点。
DOM 相当古老,并且不是使用 xml 的最简单方法,无论是在 Java 中还是在任何其他平台中(因为它是一个标准接口,在几乎所有平台上都相同)。
您尝试过 jdom 或 dom4j 吗?
yes, you cannot reuse any node. In a DOM, each node has a parent, and only one parent, once you attach a node (be it a text node or an element), that node is attached and should not be attached to any other parent node if not detached first.
DOM is rather ancient, and is not the easiest way to work with xml, not in java nor in any other platform (since it's a standard interface which is the same on almost all platforms).
Have you tried jdom or dom4j?