当前位置:网站首页>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 list
fromgetElementsByTagName()
Methods andchildNodes
Property 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 list
fromgetElementsByTagName()
Methods andattributes
Property returnsAnd then through something like
map
The way of key value pair , Take the attribute value askey
Retrieve 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 nodesfirstChild
lastChild
nextSibling
: 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
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 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
nodeValue
Attribute is used to modify the Text valuex.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
andgetAttributeNode()
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 node
nodeValue
The 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 node
removeAttribute(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 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 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 object
Call the method , It's inx object
Add a child node after the existing nodeinsertBefore(node1,node2)
Method : ifx object
Call the method , It's innode2
Insert before the child nodenode1
Child 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 ;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
边栏推荐
- When I forget how to write SQL, I
- Legion is a network penetration tool
- IPv6 comprehensive experiment
- Use the data to tell you where is the most difficult province for the college entrance examination!
- Write a program to define an array with 10 int elements, and take its position in the array as the initial value of each element.
- What is devsecops? Definitions, processes, frameworks and best practices for 2022
- Whether a person is reliable or not, closed loop is very important
- 今日睡眠质量记录78分
- Dichotomy search (C language)
- 【Day2】 convolutional-neural-networks
猜你喜欢
Use the data to tell you where is the most difficult province for the college entrance examination!
IPv6 comprehensive experiment
Introduction to extensible system architecture
Quick sort (C language)
Evolution from monomer architecture to microservice architecture
Realsense of d435i, d435, d415, t265_ Matching and installation of viewer environment
When I forget how to write SQL, I
Dynamic memory management
DML statement of MySQL Foundation
Vs201 solution to failure to open source file HPP (or link library file)
随机推荐
Dichotomy search (C language)
System.currentTimeMillis() 和 System.nanoTime() 哪个更快?别用错了!
On binary tree (C language)
Devop basic command
Custom type: structure, enumeration, union
Sword finger offer 31 Stack push in and pop-up sequence
Time complexity and space complexity
/*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*/
[FAQ] summary of common causes and solutions of Huawei account service error 907135701
使用 C# 提取 PDF 文件中的所有文字(支持 .NET Core)
2020-03-28
Doris / Clickhouse / Hudi, a phased summary in June
Jianzhi offer 04 (implemented in C language)
Exercise 8-10 output student grades (20 points)
Write a program to define an array with 10 int elements, and take its position in the array as the initial value of each element.
uniapp---初步使用websocket(长链接实现)
leetcode1229. Schedule the meeting
Rhsca day 11 operation
Pod management
Seven examples to understand the storage rules of shaped data on each bit