Example 8: XML DOM API with JavaScript
Parse, traverse and modify XML directly in the browser, without reloading the page
🎯 What does this example cover?
A diferencia de los ejemplos anteriores (procesados en PHP en el servidor), este funciona enteramente en tu navegador, con JavaScript. Usa DOMParser para convertir texto en un documento XML real, createElement() /
appendChild() para modificarlo, y XMLSerializer para volver a convertirlo en texto. Todo ocurre en memoria, al instante, sin enviar nada al servidor.
XML Editor
Add book (createElement + appendChild)
Search by title (getElementsByTagName)
Status
Current XML document (serialized with XMLSerializer)
📖 Code Explanation
Complete JavaScript Code (summarized)
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(texto, "application/xml");
const raiz = xmlDoc.getElementsByTagName("biblioteca")[0];
const nodoLibro = xmlDoc.createElement("libro");
const nodoTitulo = xmlDoc.createElement("titulo");
nodoTitulo.textContent = "Nuevo libro";
nodoLibro.appendChild(nodoTitulo);
raiz.appendChild(nodoLibro);
const serializer = new XMLSerializer();
const textoFinal = serializer.serializeToString(xmlDoc);
📝 DOMParser
What does it do? Converts a text string into an XML document the browser can navigate, just like simplexml_load_string() does in PHP, but on the client side.
💡 Concept: parsererror
If the XML isn't valid, parseFromString doesn't throw an exception: it inserts an <parsererror> element inside the resulting document, and you have to check for it manually with querySelector('parsererror').
📝 createElement() and appendChild()
raiz.appendChild(nodo);
What does it do? createElement() creates a new node (still "floating", with no place in the tree). appendChild() inserts it as the last child of another node, modifying the in-memory DOM tree.
📝 XMLSerializer
What does it do? Does the reverse process of DOMParser: converts the (now modified) DOM tree back into an XML text string, which is what's shown in the editor and in the output.
🎯 Key Concepts Learned
DOM XML in the browser
DOMParserconverts text into a treeXMLSerializerconverts a tree into text- Everything happens without reloading the page
Modifying the tree
createElement()creates new nodesappendChild()inserts themtextContentsets their content
Traversing and Searching
getElementsByTagName()searches by tag- Returns an array-like collection
- It can be combined with
.textContentto filter
💪 Practical Exercise
Expand DOM manipulation
- Parse the XML, add two new books and search by a word from the title
- Deliberately cause an error (delete a closing tag) and observe the
parsererrormessage - Think about how you'd remove a book from the document (hint:
removeChild()on its parent node)
Remove a node with removeChild()
const libros = xmlDoc.getElementsByTagName("libro");
const primerLibro = libros[0];
primerLibro.parentNode.removeChild(primerLibro);
removeChild() is called on the parent, telling it exactly which child to remove.