当前位置:网站首页>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
边栏推荐
- Velodyne configuration command
- Vanishing numbers
- Lavel document reading notes -how to use @auth and @guest directives in lavel
- Pod management
- RHCE day 3
- Summary of several job scheduling problems
- System. Currenttimemillis() and system Nanotime (), which is faster? Don't use it wrong!
- C language - stack
- Quick sort (C language)
- MySQL case
猜你喜欢

Some summaries of the third anniversary of joining Ping An in China
![[200 opencv routines] 218 Multi line italic text watermark](/img/3e/537476405f02f0ebd6496067e81af1.png)
[200 opencv routines] 218 Multi line italic text watermark

用数据告诉你高考最难的省份是哪里!

Remove linked list elements

system design

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

uniapp 处理过去时间对比现在时间的时间差 如刚刚、几分钟前,几小时前,几个月前

Safety reinforcement learning based on linear function approximation safe RL with linear function approximation translation 2

The bamboo shadow sweeps the steps, the dust does not move, and the moon passes through the marsh without trace -- in-depth understanding of the pointer

Dynamic memory management
随机推荐
Hlk-w801wifi connection
Rhcsa day 10 operation
Reasons and solutions for the 8-hour difference in mongodb data date display
Exercise 7-2 finding the maximum value and its subscript (20 points)
Dynamic memory management
Work order management system OTRs
MySQL case
OSPF comprehensive experiment
基于线性函数近似的安全强化学习 Safe RL with Linear Function Approximation 翻译 1
Rhcsa operation
From programmers to large-scale distributed architects, where are you (2)
/*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*/
OSPF summary
Reprint: summation formula of proportional series and its derivation process
Number of relationship models
Check 15 developer tools of Alibaba
Four characteristics and isolation levels of database transactions
Press the button wizard to learn how to fight monsters - identify the map, run the map, enter the gang and identify NPC
如果不知道這4種緩存模式,敢說懂緩存嗎?
【Day1】 deep-learning-basics