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);
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.
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.
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"));
appendChild()
method adds a node after the last child node of the specified element node.
setTextContent()
Replace the text content by this one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With