当前位置:网站首页>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 ?

- 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 .
- First XML The parser will XML Load document into XML DOM In the object
- XML DOM Object contains access 、 operation XML Document method function
- 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 )

Typical method

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 #documentnodeValue:Can read but write 、 Of the text node nodeValue It's the text itself 、 The attribute node is the value of the attributenodeType:
6.XML DOM List of nodes (Node List)
The node listfromgetElementsByTagName()Methods andchildNodesProperty returnscharacteristic :- 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 listfromgetElementsByTagName()Methods andattributesProperty returnsAnd then through something like
mapThe way of key value pair , Take the attribute value askeyRetrieve the corresponding property and call the functiongetNameItem()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 nodechildNodes: Find the child node of the current node , Return a list of nodesfirstChildlastChildnextSibling: The next sibling of the current nodepreviousSibling: The previous sibling node of the current node
10. Operate on the node (js Code )
10.1 Get node value
nodeValueProperty 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 nodexmlDoc = loadXMLDoc("book.xml"); x = xmlDoc.getElementByTagName("title")[0].getAttributeNode("lang");//lang It's the property name txt = x.nodeValue;
10.2 Modify node values
nodeValueAttribute is used to modify the Text valuex.nodeValue="Easy Cooking";// By direct assignmentsetAttribute()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 valuenodeValueandgetAttributeNode()Use together to change the value of the attributex=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 nodenodeValueThe way of attribute value substitution , Delete a text nodexmlDoc.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 noderemoveAttribute(attribute_name)Delete the attribute node according to its namex[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 nodexmlDoc=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 newNodenodeValueProperty substitution Text node The text in the ( Same as 10.3 Usage of )
10.5 Create nodes
createElement()Method to create a new element nodecreateAttribute()Used to create a new attribute node , Create first, then assigncreateTextNode()Method to create a new text nodecreateCDATASection()Method to create a new CDATA section nodecreateComment()Method to create a new annotation node
10.6 Add a node
appendChild()Method : ifx objectCall the method , It's inx objectAdd a child node after the existing nodeinsertBefore(node1,node2)Method : ifx objectCall the method , It's innode2Insert before the child nodenode1Child nodeinsertData()Method to insert data into an existing text nodex=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 ;trueIt means copying the attributes and child nodes of the cloned node
The book follows : How to use C# Language parsing operation XML file
边栏推荐
- IPv6 comprehensive experiment
- Static comprehensive experiment ---hcip1
- AUTOSAR从入门到精通100讲(106)-域控制器中的SOA
- Ruby time format conversion strftime MS matching format
- Exercise 7-3 store the numbers in the array in reverse order (20 points)
- Realsense d435 d435i d415 depth camera obtains RGB map, left and right infrared camera map, depth map and IMU data under ROS
- Lavel document reading notes -how to use @auth and @guest directives in lavel
- Basic principle of servlet and application of common API methods
- Uniapp--- initial use of websocket (long link implementation)
- Development guidance document of CMDB
猜你喜欢

转载:等比数列的求和公式,及其推导过程

When I forget how to write SQL, I

BGP ---- border gateway routing protocol ----- basic experiment

Remove linked list elements

leetcode1-3

From programmers to large-scale distributed architects, where are you (2)

今日睡眠质量记录78分

Reprint: summation formula of proportional series and its derivation process

对于程序员来说,伤害力度最大的话。。。

Safety reinforcement learning based on linear function approximation safe RL with linear function approximation translation 1
随机推荐
The future education examination system cannot answer questions, and there is no response after clicking on the options, and the answers will not be recorded
/*The rewriter outputs the contents of the IA array. It is required that the type defined by typedef cannot be used in the outer loop*/
Some summaries of the third anniversary of joining Ping An in China
leetcode1229. Schedule the meeting
AUTOSAR from getting started to mastering 100 lectures (106) - SOA in domain controllers
原生div具有编辑能力
Student achievement management system (C language)
Latex learning insertion number - list of filled dots, bars, numbers
Exercise 9-1 time conversion (15 points)
leetcode729. My schedule 1
入职中国平安三周年的一些总结
Reasons and solutions for the 8-hour difference in mongodb data date display
Basic data types of MySQL
system design
Crawl Zhejiang industry and trade news page
Dos:disk operating system, including core startup program and command program
Collection of practical string functions
Software sharing: the best PDF document conversion tool and PDF Suite Enterprise version sharing | with sharing
Occasional pit compiled by idea
MySQL case