当前位置:网站首页>Learning XML DOM -- a typical model for parsing XML documents

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

2022-07-04 10:31:00 Big bear loves to work

The book follows : About XML Structure 、 characteristic 、 attribute

XML DOM Learning notes

If you want to parse 、 Read 、 write in XML, Then learn XML DOM

1.XML DOM What is it ?

 Please add a picture description

  • XML DOM All defined XML The objects and properties of the element , And how to access them ( Interface )
  • XML DOM It's for getting 、 change 、 add to 、 Delete XML The standard of elements

2.XML DOM node

  • Document nodes 、 Element nodes 、 Text node ( Text in element )、 Attribute node 、 Comment node

  • Be careful : Text is stored directly in the text node , Text nodes are stored in element nodes

<book>
    <title> The romance of The Three Kingdoms </title> 
</book>

3.DOM Node tree

  • XML DOM hold XML A document is treated as a tree structure . This tree structure is called Node tree ,XML Data is constructed in the form of a tree
  • All nodes can be accessed through this tree . You can modify or delete their contents , You can also create new elements
  • The parent node in the tree here 、 Child node 、 At the same level ( brother ) The concept of node is the same as that of tree in data structure
<bookstore>
    <book category="cooking">
        <title lang="en">Everyday Italian</title>	// First child node 
        <author>Giada De Laurentiis</author>
        <year>2005</year>
        <price>30.00</price>						// The last child node 
    </book>
</bookstore>

4.XML Parser

  • working principle : High level programming language through XML Parser , To access and operate XML file .
    1. First XML The parser will XML Load document into XML DOM In the object
    2. XML DOM Object contains access 、 operation XML Document method function
    3. Then the high-level programming language calls XML DOM To access XML Each node of

5.XML Properties and methods

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

  • Typical properties ( The attribute here refers to the attribute of object-oriented language , instead of XML Attribute of element )
     Please add a picture description

  • Typical method
     Please add a picture description

  • XML DOM Every node in is an object , Its possession :

    • Important attributes :

      • nodeName: read-only 、 Of the text node nodeName yes #text、 Of the document node nodeName yes #document

      • nodeValue: Can read but write 、 Of the text node nodeValue It's the text itself 、 The attribute node is the value of the attribute

      • nodeType:

         Please add a picture description

6.XML DOM List of nodes (Node List)

  • The node list from getElementsByTagName() Methods and childNodes Property returns
  • characteristic :
    • The order of nodes in the list is the same as XML The document shall prevail 、 Index from 0 Start
    • If you delete or add elements , The list will be automatically updated

7.XML DOM Property list (js Code )

  • Property list from getElementsByTagName() Methods and attributes Property returns

  • And then through something like map The way of key value pair , Take the attribute value as key Retrieve the corresponding property and call the function getNameItem()

    xmlDoc=loadXMLDoc("books.xml");
    x=xmlDoc.getElementsByTagName("book")[0].attributes;
    document.write(x.getNamedItem("category").nodeValue);
    document.write("<br>" + x.length);
    

8.XML DOM Traversing the 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 a XML String of form 
 
parser = new DOMParser();								// Instantiate a DOM Parser 
xmlDoc = parser.parseFromString(text,"text/xml");	   // Use the parser to parse XML character string 
 
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>";// Add up 
}
document.getElementById("demo").innerHTML = txt;// Show 

9. Find other nodes through node attributes

  • parentNode: Find the parent node of the current node
  • childNodes: Find the child node of the current node , Return a list of nodes
  • firstChild
  • lastChild
  • nextSibling: The next sibling of the current node
  • previousSibling: The previous sibling node of the current node

10. Operate on the node (js Code )

10.1 Get node value
  • nodeValue Property is used to get the Text value

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

    • Attribute nodes have text values
    xmlDoc = loadXMLDoc("book.xml");
    txt = xmlDoc.getElementByTagName("title")[0].getAttribute();
    
  • getAttributeNode() Method returns Attribute node

    xmlDoc = loadXMLDoc("book.xml");
    x = xmlDoc.getElementByTagName("title")[0].getAttributeNode("lang");//lang It's the property name 
    txt = x.nodeValue;
    
10.2 Modify node values
  • nodeValue Attribute is used to modify the Text value

    x.nodeValue="Easy Cooking";// By direct assignment 
    
  • setAttribute() Method to change the value of an existing attribute or create a new attribute

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

    x=xmlDoc.getElementsByTagName('book');
    y=x[0].getAttributeNode("category");
    y.nodeValue = "food";
    
10.3 Delete node value
  • removeChild() Method to delete 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];	//  hold x Set as the node to delete 
    xmlDoc.documentElement.removeChild(x);		//  Delete node x
    
    x.parentNode.removeChild(x);				//  Navigate to x Parent node , And then delete x Child node ( Delete yourself )
    
    y = x.childNodes[0];
    x.removeChild(y);							//  Delete text node 
    
  • nodeValue The way of attribute value substitution , Delete a text node

    xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue = "";
    //xmlDoc representative XML File object 
    //xmlDoc.getElementsByTagName("title") The representative label is “title” The list of elements 
    //xmlDoc.getElementsByTagName("title")[0] Represents the first element of the element list --- One label is “title” The elements of 
    //xmlDoc.getElementsByTagName("title")[0].childNodes The representative label is “title” List of child nodes of the element , Text node 
    //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) Delete the attribute node according to its name

    x[0].removeAttribute("category");
    
  • removeAttributeNode(node) Delete all attributes of the node according to the node

10.4 Replace node values
  • replaceChild() Method to replace the specified node

    xmlDoc=loadXMLDoc("books.xml"); 	//  load XML File to object xml Doc
    x = xmlDoc.documentElement;			// x Root node 
    //  Create a new book Elements 、title Elements 、node node 
    newNode = xmlDoc.createElement("book");	//  establish book Elements 
    newTitle = xmlDoc.createElement("title");//  establish title Elements 
    newText = xmlDoc.createTextNode("A Notebook");// Create text node 
    
    //  Form a parent-child relationship by adding 
    newTitle.appendChild(newText);	//  Add a text node to newTitle In the elements 
    newNode.appendChild(newTitle);	//  take title Element added to newNode in 
    
    //  Replacement node 
    y = x.getElementByTagName("book")[0]// y Is the first child node 
    x.replaceChild(newNode,y);// take x Child nodes of y Replace replace by newNode
    
  • nodeValue Property substitution Text node The text in the ( Same as 10.3 Usage of )

10.5 Create nodes
  • createElement() Method to create a new element node
  • createAttribute() Used to create a new attribute node , Create first, then assign
  • createTextNode() Method to create a new text node
  • createCDATASection() Method to create a new CDATA section node
  • createComment() Method to create a new annotation node
10.6 Add a node
  • appendChild() Method : if x object Call the method , It's in x object Add a child node after the existing node

  • insertBefore(node1,node2) Method : if x object Call the method , It's in node2 Insert before the child node node1 Child node

  • insertData() Method to insert data into an existing text node

    x=xmlDoc.getElementsByTagName("title")[0].childNodes[0];
    
    x.insertData(0,"Easy ");	//  stay 0 Position start , Insert "Easy " character string 
    
10.7 Clone node
  • cloneNode(true/false) Method to create a copy of the specified node ;
    • true It means copying the attributes and child nodes of the cloned node

The book follows : How to use C# Language parsing operation XML file

原网站

版权声明
本文为[Big bear loves to work]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141418111752.html