差異

2013-02-28 20 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() 

用這個替換文本內容。