Dom access XML

Source: Internet
Author: User

Dom access XML
I. xml file format.
Ii. Overview.
Iii. Several operations.
3.1 add...
3.2 modify...
3.3 Delete...
3.4 copy to another XML
3.5 except all...
4. Supplement.
5. XPath syntax.
5.1 more common...
5.1.1 select all the elements of this class...
5.1.2 conditional selection elements...
5.1.3 select an element that contains an attribute...
5.1.4 select an element that contains attributes...
5.1.5 select an element whose property value is...
Below 5.2 is my Excerpt from the Internet ....
5.2.1 document 1...
5.2.2 document 2...

Dom access XML

InProgramThere are generally two models for accessing and then operating XML files, namely using dom (Document Object Model) and stream model. The following is my study notes, mainly to learn how to use Dom to access XML.

I. xml file format

The following is an XML file called contact. xml.

<? XML version = "1.0" encoding = "UTF-8"?>
<Xmltt>
<Contactdetails>
<Contact>
<Name>
<First> Luo </first>
<Last> Luo </last>
</Name>
<Note> luoandluo </Note>
</Contact>
</Contactdetails>
</Xmltt>

Ii. Overview

The advantage of Dom is that it allows you to edit and update XML documents and randomly access the data in the documents. You can use XPath to query the data. However, the disadvantage of Dom is that it needs to load the entire document to the memory at a time. For large documents, this will cause resource problems. The stream model solves this problem well because it uses the stream concept to access XML files, that is, it only has the current node in the memory at any time, but it also has its shortcomings. It is read-only and only forward, and cannot perform backward navigation in the document. (Sorry, they are all copied.) Do you understand it.

Iii. Several operations

3.1 add

String strxmlpath;
Strxmlpath = server. mappath ("contact. xml ");
Xmldocument xdoc = new xmldocument ();
Xdoc. Load (strxmlpath );
Xmlelement xele = NULL;

// First, check whether the specified object already exists.
Xele = (xmlelement) xdoc. selectsinglenode (string. format ("// name [first = '{0}' and last = '{1}']", firstname. text, lastname. text ));

If (xele! = NULL) //
{< br> label3.text = "already exist";
}< br> else // does not exist, you can add
{< br> xmldocumentfragment xdocfrag = xdoc. createdocumentfragment ();
xmlelement xcontact = xdoc. createelement ("Contact");
xmlelement xname = xdoc. createelement ("name");
xmlelement xfirst = xdoc. createelement ("first");
xfirst. innertext = firstname. text;
xmlelement xlast = xdoc. createelement ("last");
xlast. innertext = lastname. text;
xname. appendchild (xfirst);
xname. appendchild (xlast);
xmlelement xnote = xdoc. createelement ("NOTE");
xnote. innertext = firstname. text + "and" + lastname. text;
xcontact. appendchild (xname);
xcontact. appendchild (xnote);
xdocfrag. appendchild (xcontact);
xmlnode xroot = NULL;
xroot = xdoc. selectsinglenode ("// contactdetails"); // contactdetails

If (xroot! = NULL)
{
// Xroot. appendchild (xdocfrag. firstchild); // Add it to the end
Xroot. prependchild (xdocfrag. firstchild); // Add it to the beginning as the first subnode
// There are also insertbefore, insertafter (new, old)
Xdoc. Save (strxmlpath );
Label3.text = "add sucess ";//
}
Else
{
Label3.text = "add failed ";
}

3.2 modify

String STR = server. mappath ("contact. xml ");
Xmldocument xdoc = new xmldocument ();
Xdoc. Load (STR );
Xmlelement xele = NULL;

// Check whether the element to be modified exists

xele = (xmlelement) xdoc. selectsinglenode (string. format ("// name [first = '{0}' and last = '{1}']", firstname. text, lastname. text);
If (xele = NULL) // does not exist
{< br> label5.text = "no exist ";
}< br> else // exists
{< br> // The following method
/* xele. childnodes [0]. innerxml = firstname. text + "replace";
xele. childnodes [1]. innerxml = lastname. text + "replace";
xele. nextsibling. innerxml = firstname. text + "and" + lastname. text + "replace"; */

// You can also
// True indicates recursively cloning the child tree under a specified Node
Xmlelement xnodecopy = (xmlelement) xele. clonenode (true );//
Xnodecopy. childnodes [0]. innerxml = firstname. Text + "replace ";
Xnodecopy. childnodes [1]. innerxml = lastname. Text + "replace ";
// Xnodecopy. nextsibling. innerxml = firstname. Text + "and" + lastname. Text + "replace ";
// Xnodecopy. parentnode. replaceChild (xnodecopy, xele); // This is incorrect, because xnodecopy only clones This vertex and its Child vertex and does not have a parent vertex.
Xele. parentnode. replaceChild (xnodecopy, xele );
}
Xdoc. Save (STR );

}

3.3 Delete

String STR;
STR = server. mappath ("contact. xml ");
Xmldocument xdoc = new xmldocument ();
Xdoc. Load (STR );
Xmlelement xele = NULL;
// Find whether a specified vertex exists
Xele = (xmlelement) xdoc. selectsinglenode (string. format ("// name [first = '{0}' and last = '{1}']", firstname. text, lastname. text ));

If (xele! = NULL) // exists
{
Xele. parentnode. parentnode. removechild (xele. parentnode );
Label6.text = "delete sucess ";
}
Else
{
Label6.text = "no find ";
}
Xdoc. Save (STR );

3.4 copy to another XML

String strsrc, strdst;
Strsrc = server. mappath ("contact. xml"); // source file
Strdst = server. mappath ("DST. xml"); // target file
Xmldocument xsrcdoc = new xmldocument ();
Xsrcdoc. Load (strsrc );
Xmldocument xdstdoc = new xmldocument ();
Xdstdoc. Load (strdst );
Xmlnodelist xlist = NULL;
Xmlnode xdstnode = NULL;
// Assume that the contactdetails element already exists in the target XML.
Xdstnode = xdstdoc. selectsinglenode ("// contactdetails ");
Xlist = xsrcdoc. selectnodes ("// contact"); // select all vertices
If (xlist! = NULL & xdstnode! = NULL)
{
Foreach (xmlnode xnode in xlist)
{
Xmlnode xnodeimp = xdstdoc. importnode (xnode, true); // nodes of different XML must be imported before they can be used in their own XML
Xdstnode. appendchild (xnodeimp );
}
}

Xdstdoc. Save (strdst );

3.5 except all

String strdst;
Strdst = server. mappath ("DST. xml ");
Xmldocument xsrcdoc = new xmldocument ();
Xsrcdoc. Load (strdst );
// Xsrcdoc. documentelement. firstchild. removeall (); // the header node is left.
Xsrcdoc. documentelement. removeall (); // delete all nodes
Xsrcdoc. Save (strdst );

Iv. Supplement

It can be seen from the prependchild, appendchild, replaceChild, removechild, and appendchild functions that all their operations are parent elements. member functions (Operations). Therefore, you must first find the parent element, which can be found by node. parentnode.
Take a closer look at the classes used, many of which are derived directly or indirectly from xmlnode.

V. XPath syntax

5.1 common
5.1.1 select all elements of this class
// Name
All name elements in contact. xml

5.1.2 conditional Selection Elements

// Name [firstname = 'flypig' and lastname = 'luo']
Name element of firstname = 'flypig' and lastname = 'luo' in contact. xml

5.1.3 select an element with a certain attribute

// CD [@ Country]

Select all CD elements containing the country attribute.

5.1.4 select an element with attributes

// CD [@ *]

Select all CD elements with attributes

5.1.5 select an element whose property value is **

// CD [@ Country = 'U']

Select the CD element whose country attribute value is UK.

Below 5.2 are extracted from the Internet.

5.2.1 document 1

XPath is the XML query language, which is similar to SQL. The XML below is used as an example to introduce the XPath syntax.
<? XML version = "1.0" encoding = "ISO-8859-1"?>
<Catalog>
<CD Country = "USA">
<Title> empire burlesque </title>
<Artist> Bob Dylan </artist>
<Price> 10.90 </price>
</Cd>
<CD Country = "UK">
<Title> hide your heart </title>
<Artist> Bonnie Taylor </artist>
<Price> 9.90 </price>
</Cd>
<CD Country = "USA">
<Title> Greatest Hits </title>
<Artist> Dolly Parton </artist>
<Price> 9.90 </price>
</Cd>
</CATALOG>

Locate a node

XML is a tree structure, similar to the folder structure in the file system, and XPath is similar to the path naming method in the file system. However, XPath is a pattern that selects all nodes in the XML file whose path conforms to a pattern. For example, to select all the price elements in CD under catalog, you can use:
/CATALOG/CD/price
If the beginning of xpath is a slash (/), it indicates that this is an absolute path. If there are two diagonal lines (//) at the beginning, all elements in the file that match the pattern will be selected, even at different layers in the tree. The following syntax Selects all elements in the file called Cd (all layers in the tree will be selected ):
// CD
Select unknown element
Use the asterisk (wildcards, *) to select unknown elements. The following syntax Selects all child elements of/CATALOG/CD:

/CATALOG/CD /*
The following syntax Selects all child elements of catalog, including price as the child element.
/CATALOG/*/price
The following syntax Selects all elements with two parent nodes called Price.
/*/Price
The following syntax Selects all elements in the file.
//*

Note that to access non-hierarchical elements, the XPath syntax must start with two diagonal lines (//). To access unknown elements, use the asterisk (*), an asterisk can only represent an element with an unknown name, but cannot represent an element with an unknown level.

Select Branch
Use brackets to select branch. The following syntax extracts the first element named CD from the child element of catalog. The XPath definition does not contain the 0th element.

/CATALOG/CD [1]

The following syntax selects the last CD element in catalog: (xpathj does not define the first () function. In the preceding example, [1] can be used to retrieve the first element.

/CATALOG/CD [last ()]

The following syntax Selects all/CATALOG/CD elements containing the price sub-element.

/CATALOG/CD [price]

The following syntax Selects all/CATALOG/CD elements whose price value is 10.90.

/CATALOG/CD [price = 10.90]

The following syntax selects the price element of all/CATALOG/CD elements whose value is equal to 10.90.

/CATALOG/CD [price = 10.90]/price

Select more than one path
You can select more than one path by using the or operand (|. For example:

/CATALOG/CD/Title | CATALOG/CD/artist

Select All title and artist Elements

// Title | // artist

Select All title, artist, and price elements

// Title | // artist | // price

Select attributes

In XPath, you can select attributes in addition to elements. All attributes start. For example, select all the attributes in the file called country:

// @ Country

Select all CD elements containing the country attribute:

// CD [@ Country]

The following syntax Selects all CD elements containing attributes

// CD [@ *]

The following syntax selects the CD element whose country attribute value is UK.

// CD [@ Country = 'U']

5.2.2 document 2
About xpath

Node matching path xpath

In the process of using XSL for conversion, the concept of matching is very important. In the template declaration statement XSL: template match = "" and template application statement XSL: Apply-templates select = "", the Section enclosed by quotation marks must be able to precisely locate the node. The specific Positioning method is provided in XPath.

In addition, you can use XPath to search and locate XML documents.

The purpose of introducing XPath is to find a node element accurately when matching the XML document structure tree. You can compare XPathCompositionFile Management path: through the file management path, you can find the desired file according to certain rules. Similarly, according to the rules set by XPath, you can also easily find any node in the XML structure document tree.

Before introducing the matching rules of XPath, let's take a look at some basic concepts about XPath. The first thing to talk about is the XPath data type. XPath can be divided into four data types:

Node-Set)
A node set is a set of nodes that meet the conditions returned by path matching. Other types of data cannot be converted to a node set.

Boolean)
The condition matching value returned by a function or Boolean expression is the same as the Boolean value in a general language and has two values: true and false. Boolean values can be converted to numeric and string types.

String)
A string is a collection of characters. XPath provides a series of string functions. A string can be converted to data of the numeric or boolean type.

Number)
In XPath, the value is a floating point number, which can be a 64-bit double-precision floating point number. In addition, it includes some special descriptions of numerical values, such as non-numerical Nan (not-a-number), positive infinity, negative infinity-infinity, and positive and negative 0. The integer value of number can be obtained through the function. In addition, the value can also be converted to boolean and string types.

The last three data types and othersProgramming LanguageThe corresponding data type is similar, but the first data type is a unique product of the XML document tree. In addition, because XPath contains a series of operations on the document structure tree, it is also necessary to understand the XPath node type. Because of the logical structure of the XML document, an XML file can contain elements, CDATA, comments, processing instructions, and other logical elements. The elements can also contain attributes and define namespaces using attributes. Correspondingly, in XPath, nodes are divided into seven node types:

Root Node)
The root node is the top layer of a tree, and the root node is unique. All other element nodes on the tree are their child nodes or descendant nodes. The root node is processed in the same way as other nodes. In XSLT, tree matching always starts from the root node.

Element Node)
An element node corresponds to every element in the document. A child node of an element node can be an element node, a comment node, a processing command node, and a text node. You can define a unique ID for an element node.
Each element node can have an extension. It consists of two parts: one is the namespace URI and the other is the local name.

Text Node)
A text node contains a set of character data, that is, the characters contained in CDATA. No text node is adjacent to any sibling text node, and the text node has no extension.

Attribute nodes)
Each element node has an associated set of attribute nodes. The element is the parent node of each attribute node, but the attribute node is not a child node of its parent element. This means that the child node of the element can match the attribute node of the element, but in turn it is not true, only one-way. Furthermore, attribute nodes of elements are not shared, that is, different element nodes do not have the same attribute node.
Processing of default properties is equivalent to defining properties. If an attribute is declared in DTD but declared as # implied, and this attribute is not defined in the element, the attribute node of the element does not contain this attribute.
In addition, the attribute nodes corresponding to the attribute do not have namespace declarations. The namespace attribute corresponds to another type of node.

Namespace Node)
Each element node has a related namespace node set. In XML documents, namespaces are declared by retaining attributes. Therefore, in XPath, such nodes are very similar to attribute nodes, and their relationships with parent elements are unidirectional, it is not shared.

Processing Instruction nodes)
The processing command node corresponds to each processing command in the XML document. It also has an extension. The local name of the extension points to the processing object, and the namespace part is empty.

Comment nodes)
The comment node corresponds to the comment in the document. Next, we construct an XML document tree:

Now, we can implement some basic methods to match nodes in XML using XPath.

Path Matching
Path Matching is similar to the expression of the file path, which is easy to understand. There are several symbols:

Letter Number

Meaning

For example

Matching result
/

Indicates the Node path

/A/C/d
Node "A" subnode "C" subnode "D", that is, d node whose ID value is D2
/
Root Node
//
All elements whose paths end with the specified sub-path after "//"

// E
All Eelements. The result is all three Eelements.
 
// C/E
All the eElements whose parent node is C are Eelements whose ID values are E1 and E2.

*
Path wildcard

/A/B/C /*
Element A → Element B → all child elements under Element C, that is, Element B whose name is B, Element D whose ID is D1, and two Eelements whose ID value is E1 and E2

/*/D
There are two levels of node D elements. The matching result is the D element with the ID value of D2.

//*
All elements

|
Logic or

// B | // C
All B and C Elements

Location match
For each element, its child elements are ordered. For example:

For example

Meaning
Matching result
/A/B/C [1]
Element A → Element B → the first child element of Element C

B element whose name is B
 
/A/B/C [last ()]

Element A → Element B → last child element of Element C
Eelement whose ID is E2
 
/A/B/C [position ()> 1]
Element A → Element B → element whose position number is greater than 1 under Element C

D element with the ID value of D1 and two Eelements with the ID value

Attributes and attribute values
In XPath, attributes and attribute values can be used to match elements. Note that the attribute names of elements must have a "@" prefix before them. For example:

For example
Meaning
Matching result
// B [@ ID]
All B elements with property IDS
Two B elements whose ID values are B1 and B2

// B [@ *]
All B elements with attributes
Two B elements with the ID attribute and one B element with the name attribute
 
// B [not (@ *)]
All B elements that do not have attributes
Element A → Element B under Element C

// B [@ ID = "B1"]
B element whose ID is B1
B element under Element

Kinship match
XML documents can be categorized into tree structures, so no node is isolated. Generally, we define the attribution relationship between nodes as a kinship, such as parent, child, ancestor, descendant, and brother. These concepts can also be used for element matching. For example:

For example
Meaning
Matching result
// E/parent ::*
Parent node element of all e nodes
Element A whose ID is A1 and element C whose ID is C1
// F/ancestor ::*
Ancestor node elements of all f elements
Element A whose ID is A1 and element C whose ID is C2

/A/child ::*
Child element of
B element whose ID value is B1 and B2, C element whose ID value is C2, and Eelement without any attribute
 
/A/descendant ::*
All descendant elements of
All other elements except element
 
// F/self ::*
All elements of F
F element itself

// F/ancestor-or-self ::*
All f elements and their ancestor node Elements
F element, F element's parent node C element, and a Element
 
/A/C/descendant-or-self ::*
All elements A → c and their descendant Elements
The C element whose ID is C2, the child elements B, d, and F of this element
 
/A/C/following-Sibling ::*
Element A → all sibling node elements in the descending order of Element C
Eelement without any attribute
 
/A/C/preceding-Sibling ::*
Element A → all sibling node elements next to element C
Two B elements whose ID values are B1 and B2

/A/B/C/following ::*
Element A → Element B → all elements in the descending order of Element C
Element B with ID B2, element C without attributes, Element B without attributes, Element D with ID D2, element F without attributes, and element ewithout attributes.

/A/C/preceding ::*
Element A → all elements before element C
Element B whose ID is B2, element ewhose ID is E2, element ewhose ID is e1, Element D whose ID is D1, Element B whose name is B, and element C whose ID is C1, B element with ID B1

Condition match
Conditional matching is to use the Boolean values of some functions to match nodes that meet the conditions. The following types of functions are commonly used for condition matching: node functions, string functions, numeric functions, and Boolean functions. For example, last (), position (), and so on. These functions help us find the desired node precisely.

Functions and functions

Function
Count ()
Returns the number of nodes that meet the conditions.
 
Number () function
Convert the text in the attribute value to a value
 
Substring ()
Syntax: substring (value, start, length)

Truncate string
 
Sum () function
Sum
These functions are only part of the XPath syntax. A large number of functional functions are not introduced yet, and the XPath syntax is still evolving. Through these functions, we can implement more complex queries and operations.
Among the above matching methods, the maximum number of Path Matching is also used. Locate the node based on the given sub-path relative to the current path

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.