Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between setTextContent() and appendChild(Text)

Tags:

java

dom

xml

When creating a XML document what is the difference (if there is any) between these two methods of adding text to an element:

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

and

Element el = document.createElement("element");
Text txt = document.createTextNode("This is the text content");
el.appendChild(txt);
like image 594
HomeIsWhereThePcIs Avatar asked Feb 28 '13 04:02

HomeIsWhereThePcIs


People also ask

What is a node type in Java?

The Node interface is the primary datatype for the entire Document Object Model. It represents a single node in the document tree. While all objects implementing the Node interface expose methods for dealing with children, not all objects implementing the Node interface may have children.

What is org w3c DOM?

dom Description. Provides the interfaces for the Document Object Model (DOM) which is a component API of the Java API for XML Processing. The Document Object Model Level 2 Core API allows programs to dynamically access and update the content and structure of documents.


2 Answers

From the documentation for Element#setTextContent():

On setting, any possible children this node may have are removed and, if it the new string is not empty or null, replaced by a single Text node containing the string this attribute is set to.

Element#appendChild() does not remove existing children (except in the case that the specified child is already in the tree). Therefore

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

is equivalent to removing all children before calling el.appendChild():

for(Node n : el.getChildNodes())
{
    el.removeChild(n);
}
el.appendChild(document.createTextNode("This is the text content"));
like image 70
Matt Ball Avatar answered Oct 13 '22 11:10

Matt Ball


appendChild()

method adds a node after the last child node of the specified element node.

setTextContent()

Replace the text content by this one.

like image 42
Naresh Avatar answered Oct 13 '22 11:10

Naresh