【问题标题】:Difference between setTextContent() and appendChild(Text)setTextContent() 和 appendChild(Text) 的区别
【发布时间】:2013-02-14 04:33:48
【问题描述】:

在创建 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);

【问题讨论】:

    标签: java xml dom


    【解决方案1】:

    From the documentation for Element#setTextContent():

    在设置时,此节点可能具有的所有可能的子节点都将被删除,如果新字符串不为空或 null,则替换为包含此属性设置为的字符串的单个 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()
      

      用这个替换文本内容。

      【讨论】:

        猜你喜欢
        • 2014-06-13
        • 1970-01-01
        • 2012-03-18
        • 1970-01-01
        • 2015-03-07
        • 1970-01-01
        • 2019-11-13
        • 2022-01-21
        • 2022-12-04
        相关资源
        最近更新 更多