Working with Text Nodes
Text nodes store the character sequences that make up the content of XML elements and attributes. Text nodes cannot have child nodes because they represent content, not structure. Text nodes must be contained by element, attribute, document fragment, or entity reference nodes—they cannot be contained by the top-level document node, though the DOMDocument
object is used to create text nodes. For more information, see Textual Content.
Examples
The createTextNode
method of DOMDocument
object is used to create new text nodes, instances of XMLDOMText
.
JScript
In the following JScript example, createTextNode
is called twice—once to create a text node for an attribute value, and once to create a text node for element content.
var xmlDoc = new ActiveXObject("Msxml2.DOMDocument.5.0"); var rootElement=xmlDoc.createElement("memo"); var memoAttribute=xmlDoc.createAttribute("author"); var memoAttributeText=xmlDoc.createTextNode("Pat Coleman"); var toElement=xmlDoc.createElement("to"); var toElementText=xmlDoc.createTextNode("Carole Poland"); memoAttribute.appendChild(memoAttributeText); xmlDoc.appendChild(rootElement); rootElement.setAttributeNode(memoAttribute); rootElement.appendChild(toElement); toElement.appendChild(toElementText);
VBScript
Set xmlDoc = CreateObject("Msxml2.DOMDocument.5.0") Set rootElement=xmlDoc.createElement("memo") Set memoAttribute=xmlDoc.createAttribute("author") Set memoAttributeText=xmlDoc.createTextNode("Pat Coleman") Set toElement=xmlDoc.createElement("to") Set toElementText=xmlDoc.createTextNode("Carole Poland") memoAttribute.appendChild(memoAttributeText) xmlDoc.appendChild(rootElement) rootElement.setAttributeNode(memoAttribute) rootElement.appendChild(toElement) toElement.appendChild(toElementText)
Although you can read the textual content of a text node using its nodeValue
property, it is more common to use the text
property of the IXMLDOMElement
object to avoid problems created by elements containing multiple text, CDATA section, and entity reference nodes. The normalize
method of IXMLDOMElement
can also simplify text processing.
For more information on properties and methods of IXMLDOMText
, see IXMLDOMText.