Learning XML DOM -- a typical model for parsing XML documents

The book continues from the above: about the structure, characteristics and attributes of XML

XML DOM learning notes

If you want to parse, read, and write XML, you need to learn XML DOM

1. What is XML DOM?

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-EWipgqGw-1638092479646)(E:(5.2MarkDown notes \ image-20211125104113944.png)]

  • The XML DOM defines the objects and attributes of all XML elements, as well as the methods (interfaces) to access them
  • XML DOM is a standard for obtaining, changing, adding and deleting XML elements

2.XML DOM node

  • Document node, element node, text node (text in element), attribute node, comment node

  • Note: the text is stored directly in the text node, and the text node is stored in the element node

    <title>Romance of the Three Kingdoms</title> 

3.DOM node tree

  • XML DOM treats XML documents as a tree structure. This tree structure is called node tree, and XML data is constructed in the form of tree
  • All nodes can be accessed through this tree. You can modify or delete their contents, or create new elements
  • The concepts of parent node, child node and sibling node in the tree here are the same as those in the data structure
    <book category="cooking">
        <title lang="en">Everyday Italian</title>	//First child node
        <author>Giada De Laurentiis</author>
        <price>30.00</price>						//Last child node

4.XML parser

  • Working principle: high level programming language accesses and operates XML documents through XML parser.
    1. First, the XML parser loads the XML document into the XML DOM object
    2. XML DOM objects contain methods and functions to access and manipulate XML documents
    3. Then, the high-level programming language accesses each node of XML by calling the methods in XML DOM

5.XML attributes and methods

  • The properties and methods of XML DOM define the programming interface

  • Typical attributes (the attributes here refer to the attributes of object-oriented language, not the attributes of XML elements)

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-1WLTdMlJ-1638092479648)(E:(5.2MarkDown notes \ image-20211125154530757.png)]

  • Typical method

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-LdPAVy3h-1638092479649)(E:(5.2MarkDown notes \ image-20211125154810738.png)]

  • Each node in the XML DOM is an object that has:

    • Important attributes:

      • NodeName: read only, nodeName of text node is #text, and nodeName of document node is #document

      • NodeValue: readable and writable. The nodeValue of the text node is the text itself, and the attribute node is the value of the attribute

      • nodeType:

6. Node list of XML DOM

  • The node list is returned by the getElementsByTagName() method and the childNodes property
  • characteristic:
    • The order of nodes in the list is subject to the XML document, and the index starts from 0
    • If an element is deleted or added, the list is automatically updated

7.XML DOM attribute list (js code)

  • The attribute list is returned by the getElementsByTagName() method and the attributes attribute

  • Then, similar to the map key value pair, retrieve the corresponding attribute with the attribute value as the key, and call the function getNameItem()

    document.write("<br>" + x.length);

8.XML DOM traversal node tree (js code)

var x, i ,xmlDoc;	
var txt = "";
var text = "<book>" + 
"<title>Everyday Italian</title>" +
"<author>Giada De Laurentiis</author>" +
"<year>2005</year>" +
"</book>";												// Create an XML string
parser = new DOMParser();								//Instantiate a DOM parser
xmlDoc = parser.parseFromString(text,"text/xml");	   //Parsing XML strings using a parser
x = xmlDoc.documentElement.childNodes;	               //documentElement represents the root node
for (i = 0; i < x.length ;i++) {
    txt += x[i].nodeName + ": " + x[i].childNodes[0].nodeValue + "<br>";//accumulation
document.getElementById("demo").innerHTML = txt;//display

9. Find other nodes through node attributes

  • parentNode: find the parent node of the current node
  • childNodes: find the child nodes of the current node and return a node list
  • firstChild
  • lastChild
  • nextSibling: the next sibling node of the current node
  • previousSibling: the previous sibling node of the current node

10. Operate the node (js code)

10.1 get node value
  • The nodeValue property is used to get the text value of the node

    • Element node has no text value
    xmlDoc = loadXMLDoc("book.xml");
    x = xmlDoc.getElementsByTagName("title")[0];
    y = x.childNodes[0]//Text node
    txt = y.nodeValue;
  • The getAttribute() method returns the value of the attribute

    • The attribute node has a text value
    xmlDoc = loadXMLDoc("book.xml");
    txt = xmlDoc.getElementByTagName("title")[0].getAttribute();
  • The getAttributeNode() method returns the attribute node

    xmlDoc = loadXMLDoc("book.xml");
    x = xmlDoc.getElementByTagName("title")[0].getAttributeNode("lang");//lang is the property name
    txt = x.nodeValue;
10.2 modifying node values
  • The nodeValue property is used to modify the text value of the node

    x.nodeValue="Easy Cooking";//By direct assignment
  • The setAttribute() method changes the value of an existing attribute or creates a new attribute

    // change
    x=xmlDoc.getElementsByTagName('book');//List of element nodes labeled book
    x[0].setAttribute("category","food"); //change
    // establish
     If the property does not exist, the“ category"Is the property name“ food"Create a new property for the property value
  • nodeValue is used with getAttributeNode() to change the value of an attribute

    y.nodeValue = "food";
10.3 deleting node values
  • The removeChild() method deletes the specified node. The parameter is the node to be deleted

    • When a node is deleted, all its child nodes will also be deleted
    x=xmlDoc.getElementsByTagName('book')[0];	// Set x as the node to be deleted
    xmlDoc.documentElement.removeChild(x);		// Delete node x
    x.parentNode.removeChild(x);				// First navigate to the parent node of x, and then delete the child node of x (delete yourself)
    y = x.childNodes[0];
    x.removeChild(y);							// Delete text node
  • Delete a text node instead of the nodeValue property value

    xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue = "";
    //xmlDoc represents an XML file object
    //xmlDoc.getElementsByTagName("title") represents a list of elements labeled "title"
    //xmlDoc.getElementsByTagName("title")[0] represents the first element in the element list - an element labeled "title"
    //xmlDoc.getElementsByTagName("title")[0].childNodes represents the list of child nodes and text nodes of the element labeled "title"
    //xmlDoc.getElementsByTagName("title")[0].childNodes[0] represents the first element of the text node list
    //xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue represents the value of the first text node
  • removeAttribute(attribute_name) deletes an attribute node by name

  • removeAttributeNode(node) deletes all attributes of a node based on the node

10.4 replace node value
  • The replaceChild() method replaces the specified node

    xmlDoc=loadXMLDoc("books.xml"); 	// Load XML file to object xml Doc
    x = xmlDoc.documentElement´╝Ť			// x is the root node
    // Create a new book element, title element, node node
    newNode = xmlDoc.createElement("book");	// Create book element
    newTitle = xmlDoc.createElement("title");// Create a title element
    newText = xmlDoc.createTextNode("A Notebook");//Create text node
    // Parent child relationship by adding
    newTitle.appendChild(newText);	// Add a text node to the newTitle element
    newNode.appendChild(newTitle);	// Add the title element to the newNode
    // Replace node
    y = x.getElementByTagName("book")[0]// y is the first child node
    x.replaceChild(newNode,y);//replace the child node y of x with newNode
  • The nodeValue property replaces the text in the text node (the same usage as 10.3)

10.5 creating nodes
  • The createElement() method creates a new element node
  • createAttribute() is used to create a new attribute node, which is created first and then assigned
  • The createTextNode() method creates a new text node
  • The createCDATASection() method creates a new CDATA section node
  • The createstatement () method creates a new annotation node
10.6 adding nodes
  • appendChild() method: if the x object calls this method, a child node will be added after the existing node of the x object

  • insertBefore(node1,node2) method: if the x object calls this method, the node1 child node is inserted before the node2 child node

  • The insertData() method inserts data into an existing text node

    x.insertData(0,"Easy ");	// Starting at position 0, insert the "Easy" string
10.7 clone nodes
  • The cloneNode(true/false) method creates a copy of the specified node;
    • true means to copy the attributes and child nodes of the cloned node

Tags: Javascript xml

Posted on Sun, 28 Nov 2021 05:50:40 -0500 by BuckeyeTheDog