Conversion: XML read/write

Source: Internet
Author: User

1)

XML is a popular technology. One of the main reasons why it can attract people's interest is that it is very simple and people can easily understand and use it. Every programmer can easily understand an XML file and understand its content.

. Net contains a lot of classes that support XML, which make it as easy for programmers to program in XML as to understand XML files. In this article, I will give an example of using this class, which is the xmltextwriter class.

The xmltextwriter class allows you to write XML into a file. This class contains many methods and attributes. Using these attributes and methods makes it easier for you to process XML. To use this class, you must first create a new xmltextwriter object, and then you can add XML fragments to this object. This class contains many methods to add various types of XML elements to an XML file. The following table lists the names and descriptions of these methods:

Method
Description
 
Writestartdocument
Write XML declaration with Version 1.0
 
Writeenddocument
Disable any open element or attribute
 
Close
Close stream
 
Writedoctype
Write the doctype declaration with the specified name and optional attributes
 
Writestartelement
Write the specified start mark
 
Writeendelement
Close an element
 
Writefullendelement
Close an element and always write the complete end mark
 
Writeelementstring
Write the element containing the string value
 
Writestartattribute
Start content of the writing attribute
 
Writeendattribute
Disable the previous writestartattribute call
 
Writeraw
Manually write the original tag
 
Writestring
Write a string
 
Writeattributestring
Attribute with specified value
 
Writecdata
Write the <! [CDATA [...]> Block
 
Writecomment
Write comments containing the specified text <! --... -->
 
Writewhitespace
Write the given Blank
 
Writeprocessinginstruction
Write the processing command with spaces between the name and text, as shown below: <? Name text?>

If you are very familiar with XML, you will be able to understand these methods well. In this example, we will first create a document, add some elements, and then close the document. After adding an element, you can also add child elements, attributes, and other content. The following code creates an XML file named title.

Using system;
Using system. IO;
Using system. xml;
Public class sample
{
Public static void main ()
{
Xmltextwriter writer = new xmltextwriter ("titles. xml", null );
// Write the root element
Writer. writestartelement ("items ");
// Add sub-elements
Writer. writeelementstring ("title", "Unreal Tournament 2003 ");
Writer. writeelementstring ("title", "C & C: renegade ");
Writer. writeelementstring ("title", "dr. Seuss's ABC ");
// Close the root element and write the end tag
Writer. writeendelement ();
// Write XML into a file and disable xmltextwriter
Writer. Close ();
}
}
If you compile and execute the above Code, you will create this XML file, which contains the following content:
<Items>
<Title> unreal tours 2003 </title>
<Title> C & amp; C: renegade </title>
<Title> dr. Seuss's ABC </title>
</Items>

The above Code creates an xmltextwriter object named writer. When this object is created, it is associated with a file named titles. xml. Then, the program creates a root attribute called items, and the writestartelement method creates the start tag of this attribute. Next, the program calls the writeelementstring method to create three child elements. From the code above, you can also see that this method uses the first parameter (title in the above program) as the element tag, and the second parameter as the element value. After you add all elements, You need to disable the root element. You can call the writeendelement method to close the recently opened element. In this example, the recently opened element is the root element. When all the data has been written and the root element has been closed, you can send the information to your xmltextwriter. This means that you can call the close method to close it.

The above code is relatively simple. Next we will look at an example of using more methods and better functions in the xmltextwriter class.

Using system;
Using system. IO;
Using system. xml;
Public class sample
{
Public static void main ()
{
Xmltextwriter writer = new xmltextwriter ("mymedia. xml", null );
// Use automatic indentation for ease of reading
Writer. Formatting = formatting. indented;
// Write the root element
Writer. writestartelement ("items ");
// Start an element
Writer. writestartelement ("item ");
// Add an attribute to the previously created Element
Writer. writeattributestring ("rating", "R ");
// Add a child element
Writer. writeelementstring ("title", "The Matrix ");
Writer. writeelementstring ("format", "DVD ");
// Close the item Element
Writer. writeendelement (); // close the element
// Add spaces between nodes
Writer. writewhitespace ("\ n ");
// Use the original string to write the second element
Writer. writeraw ("<item>" +
"<Title> bloodwake </title>" +
"<Format> Xbox </format>" +
"</Item> ");
// Use a formatted string to write the third element
Writer. writeraw ("\ n <item> \ n" +
"<Title> Unreal Tournament 2003 </title> \ n" +
"<Format> Cd </format> \ n" +
"</Item> \ n ");
// Close the root element
Writer. writefullendelement ();
// Write XML into the file and close writer
Writer. Close ();
}
}
After the above Code is compiled and run, the mymedia. xml file is obtained. The content of the file is: <items>
<Item rating = "R">
<Title> the matrix </title>
<Format> DVD </format>
</Item>
<Item>
<Title> bloodwake </title>
<Format> Xbox </format>
</Item>
<Item>
<Title> unreal tours 2003 </title>
<Format> Cd </format>
</Item>
</Items>
The comments in the code above demonstrate how the functions of this program are implemented. One thing to remember is that when you call a method to start an operation, you need to call the method to end the operation in a proper place of the program. For example, if you call startelement, you must call endelement to close the element. Of course, you can add a child element between the two calls. Whenever you call the endelement method, it always closes the element opened recently using the startelement method (similar to the way stack works ).

It is very easy to use xmltextwriter, but I suggest you try the code and methods on your own. After you try it, you will find that the code can be easily integrated into your program. You should also remember that xmltextwriter is only one of the many XML classes provided by. net. Like xmltextwriter, other XML classes are also very easy to use.

 

 
2)
I am using a very stupid method, but it can help beginners understand the process of accessing XML nodes.
 
It is known that there is an XML file (bookstore. XML) as follows:
<? XML version = "1.0" encoding = "gb2312"?>
<Bookstore>
<Book genre = "Fantasy" ISBN = "2-3631-4">
<Title> Oberon's legacy </title>
<Author> corets, Eva </author>
<Price> 5.95 </price>
</Book>
</Bookstore>
 
1. Insert a <book> node to the <bookstore> node:
Xmldocument xmldoc = new xmldocument ();
Xmldoc. Load ("Bookstore. xml ");
Xmlnode root = xmldoc. selectsinglenode ("Bookstore"); // query <bookstore>
Xmlelement xe1 = xmldoc. createelement ("book"); // create a <book> node
Xe1.setattribute ("genre", "lizan red"); // you can specify the genre attribute of the node.
Xe1.setattribute ("ISBN", "2-3631-4"); // you can specify the ISBN attribute of the node.
 
Xmlelement xesub1 = xmldoc. createelement ("title ");
Xesub1.innertext = "Cs from entry to entry"; // set a text node
Xe1.appendchild (xesub1); // Add it to the <book> node
Xmlelement xesub2 = xmldoc. createelement ("author ");
Xesub2.innertext = "Hou Jie ";
Xe1.appendchild (xesub2 );
Xmlelement xesub3 = xmldoc. createelement ("price ");
Xesub3.innertext = "58.3 ";
Xe1.appendchild (xesub3 );
 
Root. appendchild (xe1); // Add it to the <bookstore> node
Xmldoc. Save ("Bookstore. xml ");
// ================================================ ==========
Result:
<? XML version = "1.0" encoding = "gb2312"?>
<Bookstore>
<Book genre = "Fantasy" ISBN = "2-3631-4">
<Title> Oberon's legacy </title>
<Author> corets, Eva </author>
<Price> 5.95 </price>
</Book>
<Book genre = "Li zanhong" ISBN = "2-3631-4">
<Title> Cs from entry to entry </title>
<Author> Hou Jie </author>
<Price> 58.3 </price>
</Book>
</Bookstore>
 
2. Modify the node: Change the genre value of the node whose genre attribute value is "Li zenhong" to "Update Li zenhong ", modify the text of the child node <author> of the node to "Yasheng ".
Xmlnodelist nodelist = xmldoc. selectsinglenode ("Bookstore"). childnodes; // obtain all the subnodes of the bookstore Node
Foreach (xmlnode Xn in nodelist) // traverses all subnodes
{
Xmlelement Xe = (xmlelement) xn; // converts the subnode type to the xmlelement type
If (Xe. getattribute ("genre") = "") // If the genre attribute value is ""
{
Xe. setattribute ("genre", "Update lizan red"); // you can change this attribute to "Update lizan red"
 
Xmlnodelist NLS = Xe. childnodes; // continue to obtain all the child nodes of the Xe subnode
Foreach (xmlnode xn1 in NLS) // traverse
{
Xmlelement xe2 = (xmlelement) xn1; // Conversion Type
If (xe2.name = "author") // If you find
{
Xe2.innertext = "Yasheng"; // modify
Break; // find and exit.
}
}
Break;
}
}
 
Xmldoc. Save ("Bookstore. xml"); // save.
// ================================================ ================
The final result is:
<? XML version = "1.0" encoding = "gb2312"?>
<Bookstore>
<Book genre = "Fantasy" ISBN = "2-3631-4">
<Title> Oberon's legacy </title>
<Author> corets, Eva </author>
<Price> 5.95 </price>
</Book>
<Book genre = "Update Li zanhong" ISBN = "2-3631-4">
<Title> Cs from entry to entry </title>
<Author> Yasheng </author>
<Price> 58.3 </price>
</Book>
</Bookstore>
 
3. Delete the genre attribute of the <book genre = "Fantasy" ISBN = "2-3631-4"> node, delete the <book genre = "Update lizan red" ISBN = "2-3631-4"> node.
Xmlnodelist xnl = xmldoc. selectsinglenode ("Bookstore"). childnodes;
 
Foreach (xmlnode Xn in xnl)
{
Xmlelement Xe = (xmlelement) xn;
If (Xe. getattribute ("genre") = "Fantasy ")
{
Xe. removeattribute ("genre"); // Delete genre attributes
}
Else if (Xe. getattribute ("genre") = "Update lizanhong ")
{
Xe. removeall (); // delete all content of the node
}
}
Xmldoc. Save ("Bookstore. xml ");
// ================================================ =====
The final result is:
<? XML version = "1.0" encoding = "gb2312"?>
<Bookstore>
<Book ISBN = "2-3631-4">
<Title> Oberon's legacy </title>
<Author> corets, Eva </author>
<Price> 5.95 </price>
</Book>
<Book>
</Book>
</Bookstore>
 
4. display all data.
Xmlnode xn = xmldoc. selectsinglenode ("Bookstore ");
 
Xmlnodelist xnl = xn. childnodes;

Foreach (xmlnode xnf in xnl)
{
Xmlelement Xe = (xmlelement) xnf;
Console. writeline (Xe. getattribute ("genre"); // display attribute values
Console. writeline (Xe. getattribute ("ISBN "));
 
Xmlnodelist xnf1 = Xe. childnodes;
Foreach (xmlnode xn2 in xnf1)
{
Console. writeline (xn2.innertext); // displays the child node text.
}
}

 

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.