Easy Tutorial
❮ Xml Namespaces Xml Http ❯

XML DOM - Advanced


XML DOM - Advanced

In earlier sections of this tutorial, we introduced the XML DOM and used the getElementsByTagName() method of the XML DOM to retrieve data from an XML document.

In this chapter, we will combine some other important XML DOM methods.

You can learn more about XML DOM in our XML DOM Tutorial.


Getting Element Values

The XML file used in the following example: books.xml.

The following example retrieves the text value of the first <title> element:

Example


Getting Attribute Values

The following example retrieves the text value of the "lang" attribute of the first <title> element:

Example


Changing Element Values

The following example changes the text value of the first <title> element:

Example


Creating New Attributes

The setAttribute() method of the XML DOM can be used to change existing attribute values or create a new attribute.

The following example creates a new attribute (edition="first") and adds it to each <book> element:

Example


Creating Elements

The createElement() method of the XML DOM creates a new element node.

The createTextNode() method of the XML DOM creates a new text node.

The appendChild() method of the XML DOM adds a child node to a node (after the last child node).

To create a new element with text content, you need to create both a new element node and a new text node, and then append it to an existing node.

The following example creates a new element (<edition>) with the text: First, and adds it to the first <book> element:

Example

Example Explanation


Deleting Elements

The following example deletes the first node of the first <book> element:

Example

Note: The result of the above example may vary depending on the browser used. Firefox treats new line characters as empty text nodes, whereas Internet Explorer does not. You can read more about this issue and how to avoid it in our XML DOM Tutorial.

❮ Xml Namespaces Xml Http ❯