C # basic knowledge-XML introduction and basic operations (10 ),

Source: Internet
Author: User

C # basic knowledge-XML introduction and basic operations (10 ),

After talking about a series of basic documents, I will start to talk about some examples. For some programs with low data size or configuration files that require local storage, XML can be used instead of the database, it is much easier to operate a single file than to operate a database. DOM (Document Object Model) and stream mode are generally used to access and operate XML in a program. DOM allows you to edit and update XML documents and randomly access the data in the documents. However, when loading XML, the entire document is loaded into the memory. The stream mode effectively solves this problem. The access to XML files adopts the concept of stream. At any time, There is only the current interface in the memory, and the disadvantage is that it is read-only, only forward, no longer in the document and then edit and Add.

XML (Extensible Markup Language) Extensible Markup Language. XML and HTML are similar in many places, but the syntax of HTML is not strict enough and loose, many formats do not have mandatory requirements, so it takes a lot of effort to handle browser compatibility issues. I have a special understanding that many different website systems have requirements for browsers, the standards are not uniform, so Google, Firefox, 360 ..... A lot of browsers are designed to adapt to the compatibility of different websites. XML has strict format requirements. For example, the elements must be displayed in a pair. XML also has a very important feature: high versatility, many programs, including the underlying data exchange between Web and App, are converted to XML for data exchange.

 

Here is a simple XML document:

1 <? Xml version = "1.0" encoding = "UTF-8" standalone = "yes"?> 2 3 <! -The following table lists students> 4 5 <student list> 6 7 <student id = "1"> 8 9 <student id> 201701 </student id> 10 11 <Name> Zhang sansan </Name> 12 13 <class> 0102 </class> 14 15 </student> 16 17 <student id = "2"> 18 19 <student id> 201702 </student id> 20 21 <Name> Li Si 4 </Name> 22 23 <class> 0102 </class> 24 25 </student> 26 27 <student id = "3"> 28 29 <student ID> 201703 </student ID> 30 31 <Name> Wang wuwu </Name> 32 33 <class> 0103 </class> 34 35 </student> 36 37 </student list>

 

1.Document Header declaration:

<? Xml version = "1.0" encoding = "UTF-8"?>

? The XML tag indicates that it is an XML document. The version is the version number, and the encoding attribute indicates that the encoding format is "UTF-8". When standalone gets "yes", it indicates that the file has not referenced other external files.

 

2.Note:

<! -- Below is the student list -->

The format of the comment is similar to that of html: <! -- "Comment content" -->. Note the following when using Annotations: 1. annotations cannot appear before XML declaration. 2. the "--" character cannot appear in the comment, for example, <! -- Below is the student -- List> 3. Annotations cannot be nested.

 

3.Root element:

<Student list> XXX </student list>

Each document must have a root element. If there is no root element, an error will occur during parsing.

 

4.An element (TAG) is a basic unit used to define data in XML. An element is defined by a tag and can be divided into non-empty tags and empty tags:

 

(1) Non-empty mark

<Student ID> 201701 </student ID>

<Name> Zhang sansan </Name>

<Class> 0102 </class>

If it is not empty, the tag contains content in the format of <tag> content <tag>

(2) Empty tag

<Student id = "1"> </student>

The empty tag contains only attributes, and the content of the two tags is empty.

 

XML is located in the System. Xml namespace. The XML structure list is as follows:

Mark

Description

XmlDocument

XML document

XmlNode

A single node in XML, such as <student list>

XmlAttribute

Attributes in XML elements

XmlText

Indicates the text content of an element or attribute.

XmlElement

Minimum element, for example, <Name> three or three </Name>

XmlComment

Content of XML comments

XmlDeclaration

Statement of the first line of the XML document

 

 

 

 

 

 

 

 

 

 

 

 

XMLDocument creation

Final effect:

<? Xml version = "1.0" encoding = "UTF-8"?>

<Student list>

<Student id = "1">

<Name> Zhang sansan </Name>

</Student>

</Student list>

Code:

1 // create an XML Document Object 2 3 XmlDocument doc = new XmlDocument (); 4 5 // declare XML header information 6 7 XmlDeclaration dec = doc. createXmlDeclaration ("1.0", "UTF-8", null); 8 9 // Add to doc object subnode 10 11 doc. appendChild (dec); 12 13 // create the root node 14 15 XmlElement root = doc. createElement ("Student List"); 16 17 doc. appendChild (root); 18 19 20 21 // create a child node 22 23 XmlElement student = doc under the root node. createElement ("student"); 24 25 // set the subnode attribute 26 27 student. setAttribute ("id", "1"); 28 29 // create a tag 30 31 XmlElement studentName = doc under the subnode. createElement ("name"); 32 33 // <Name> content 34 35 XmlText xmlText = doc. createTextNode ("three"); 36 37 // Add the content to <Name> Mark 38 39 studentName. appendChild (xmlText); 40 41 // Add the <Name> flag to the <student> marked subnode 42 43 student. appendChild (studentName); 44 45 // Add the <student> flag to the root node. <student list> 46 47 root under the child node. appendChild (student); 48 49 // The doc object is saved and written to 50 51 doc. save ("Student. xml ");

 

 XMLDocument Reading

In C #, XML can be read in three ways: XmlDocument, XmlTextReader, and Linq to Xml. In these ways, I am used to using Linq, because it is very convenient to read and filter data through Linq, however, we have not written any article about Linq. Here we use the XmlDocument method.

1 XmlDocument doc = new XmlDocument (); 2 3 // load the XML file in the root directory 4 5 doc. load ("XMLFile1.xml"); 6 7 // get the root node 8 9 XmlElement root = doc. documentElement; 10 11 // get <student> subnode 12 13 XmlNodeList personNodes = root. getElementsByTagName ("student"); 14 15 // use the foreach loop to read the set 16 17 foreach (XmlNode node in personNodes) 18 19 {20 21 string id = (XmlElement) node ). getAttribute ("id"); 22 23 string name = (XmlElement) node ). getElementsByTagName ("name") [0]. innerText; 24 25 string number = (XmlElement) node ). getElementsByTagName ("student ID") [0]. innerText; 26 27 string _ class = (XmlElement) node ). getElementsByTagName ("class") [0]. innerText; 28 29 Console. writeLine ("student Id: {0}, name: {1}, student id: {2}, class: {3}", Id, name, number, _ class ); 30 31} 32 33 Console. readKey ();

 

 Add

 

1 string xmlPath = "XMLFile1.xml"; 2 3 XmlDocument doc = new XmlDocument (); 4 5 // load the XML file 6 7 doc in the root directory. load (xmlPath); 8 9 // get the root node 10 11 XmlElement root = doc. documentElement; 12 13 14 15 XmlElement student = doc. createElement ("student"); 16 17 student. setAttribute ("id", "4"); 18 19 // Add name tag 20 21 XmlElement studentName = doc. createElement ("name"); 22 23 XmlText xmlText = doc. createTextNode ("James"); 24 25 studentName. appendChild (xmlText); 26 27 // Add student ID tag 28 29 XmlElement studentNumber = doc. createElement ("student ID"); 30 31 XmlText xmlText2 = doc. createTextNode ("201704"); 32 33 studentNumber. appendChild (xmlText2); 34 35 // Add class tag 36 37 XmlElement studentClass = doc. createElement ("class"); 38 39 XmlText xmlText3 = doc. createTextNode ("0102"); 40 41 studentClass. appendChild (xmlText3); 42 43 44 45 // Add the tag created above to the <student> tag 46 47 student. appendChild (studentName); 48 49 student. appendChild (studentNumber); 50 51 student. appendChild (studentClass); 52 53 54 55 // Add the tag created above to the <student list> root tag 56 57 root. appendChild (student); 58 59 60 61 // do not forget to save 62 63 doc in the last step. save (xmlPath );

 

 

 

 

Modify

1 string xmlPath = "XMLFile1.xml"; 2 3 XmlDocument doc = new XmlDocument (); 4 5 doc. load (xmlPath); 6 7 XmlElement root = doc. documentElement; 8 9 // filter out the qualified tags 10 11 XmlElement selectEle = (XmlElement) root. selectSingleNode ("/student list/student [@ id = '4']"); 12 13 // obtain the child element 14 15 XmlElement nameEle = (XmlElement) selectEle. getElementsByTagName ("name") [0]; 16 17 // modify the content in the <Name> tag 18 19 nameEle. innerText = "Daming"; 20 21 // do not forget to save the 22 23 doc. save (xmlPath );

 

Delete tag

Deleting and modifying are similar to filtering out qualified tags and then removing them.

1 string xmlPath = "XMLFile1.xml"; 2 3 XmlDocument doc = new XmlDocument (); 4 5 doc. load (xmlPath); 6 7 XmlElement root = doc. documentElement; 8 9 // filter out the qualified tags 10 11 XmlElement selectEle = (XmlElement) root. selectSingleNode ("/student list/student [@ id = '4']"); 12 13 // Delete the specified child element 14 15 root. removeChild (selectEle); 16 17 // do not forget to save the sentence 18 19 doc. save (xmlPath );

 


The above is the basic XML operation method. Of course, if you use Linq to Xml, it will be more flexible. If you are interested in other operations, you can directly study them.

Related Article

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.