在创建XML文档时,这两种向元素添加文本的方法之间的区别(如果有):
Element el = document.createElement("element");
el.setTextContent("This is the text content");
Run Code Online (Sandbox Code Playgroud)
和
Element el = document.createElement("element");
Text txt = document.createTextNode("This is the text content");
el.appendChild(txt);
Run Code Online (Sandbox Code Playgroud)
从以下文档Element#setTextContent():
在设置时,将删除此节点可能具有的任何子节点,如果新字符串不为空或为null,则替换为包含此属性设置为的字符串的单个Text节点.
Element#appendChild()不会删除现有的子项(除非指定的子项已经在树中).因此
el.setTextContent("This is the text content")
Run Code Online (Sandbox Code Playgroud)
相当于在调用之前删除所有孩子el.appendChild():
for(Node n : el.getChildNodes())
{
el.removeChild(n);
}
el.appendChild(document.createTextNode("This is the text content"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8794 次 |
| 最近记录: |