差异

2013-02-28 21 views
6

当创建一个XML文档的区别是什么(如果有的话)添加文本元素的这两种方法:差异

Element el = document.createElement("element"); 
el.setTextContent("This is the text content"); 

Element el = document.createElement("element"); 
Text txt = document.createTextNode("This is the text content"); 
el.appendChild(txt); 

回答

7

From the documentation for Element#setTextContent():

在设置时,任何可能的儿童这个节点可能已经被去除并且,如果新字符串不为空或空,由包含此属性设置为的字符串的单个Text节点替换。

Element#appendChild()不会删除现有的子项(除非指定的子项已经在树中)。因此

el.setTextContent("This is the text content") 

相当于删除所有儿童调用el.appendChild()前:

for(Node n : el.getChildNodes()) 
{ 
    el.removeChild(n); 
} 
el.appendChild(document.createTextNode("This is the text content")); 
2

appendChild()

方法指定元素节点的最后一个子节点之后添加一个节点。

setTextContent() 

用这个替换文本内容。