当前位置:网站首页>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
边栏推荐
- Basic principle of servlet and application of common API methods
- Work order management system OTRs
- Realsense of d435i, d435, d415, t265_ Matching and installation of viewer environment
- Delayed message center design
- Dynamic memory management
- Tables in the thesis of latex learning
- Rhcsa day 10 operation
- System.currentTimeMillis() 和 System.nanoTime() 哪个更快?别用错了!
- Press the button wizard to learn how to fight monsters - identify the map, run the map, enter the gang and identify NPC
- Huge number multiplication (C language)
猜你喜欢

Static comprehensive experiment ---hcip1

Time complexity and space complexity
![[FAQ] summary of common causes and solutions of Huawei account service error 907135701](/img/73/c4ee842475f05e2e67297fcac68779.png)
[FAQ] summary of common causes and solutions of Huawei account service error 907135701

PHP代码审计3—系统重装漏洞

Rhcsa learning practice
If you don't know these four caching modes, dare you say you understand caching?

Doris / Clickhouse / Hudi, a phased summary in June

system design

uniapp 小于1000 按原数字显示 超过1000 数字换算成10w+ 1.3k+ 显示

【Day2】 convolutional-neural-networks
随机推荐
Ruby时间格式转换strftime毫秒匹配格式
Si vous ne connaissez pas ces quatre modes de mise en cache, vous osez dire que vous connaissez la mise en cache?
Some summaries of the third anniversary of joining Ping An in China
DCL statement of MySQL Foundation
Exercise 7-4 find out the elements that are not common to two arrays (20 points)
What is devsecops? Definitions, processes, frameworks and best practices for 2022
Map container
Occasional pit compiled by idea
Huge number (C language)
VLAN part of switching technology
Safety reinforcement learning based on linear function approximation safe RL with linear function approximation translation 2
有老师知道 继承RichSourceFunction自定义读mysql怎么做增量吗?
Exercise 9-1 time conversion (15 points)
【Day1】 deep-learning-basics
【Day2】 convolutional-neural-networks
使用 C# 提取 PDF 文件中的所有文字(支持 .NET Core)
Lavel document reading notes -how to use @auth and @guest directives in lavel
基于线性函数近似的安全强化学习 Safe RL with Linear Function Approximation 翻译 2
PHP code audit 3 - system reload vulnerability
【Day2】 convolutional-neural-networks