C # How to create an XML file)

Source: Internet
Author: User
C # How to create an XML file

Introduction

With the popularization of XML and a large number of applications in Dynamic Web applications, it is also important to modify and delete XML files by using. net. A simple concept is that an XML file is no different from a large text file, and it is prior. net, many ASP developers usually use response when they need the program to output XML files. the write () method is output as an XML document.
Use response. writing () is not a good way to output XML documents. First, when we use this method to output characters to form an XML file, we are worried about whether the output characters comply with the XML specification. XML documents that do not comply with the XML specification cannot be displayed completely, such as: <,> ,&"", and ', when they appear in an XML file, we must manually find these nonstandard characters. Again, when we need to output a file containing many namespaces, response. the Code required for the write () method will become lengthy and less readable.

Fortunately ,. net Framework provides a class especially for creating XML files-system. XML. xmltextwriter uses this class to create XML files. You do not need to worry about whether the output meets the XML specifications, and the code will become very concise. This article describes how to use the xmltextwriter class to create an XML file.
XML Description

This article assumes that the reader has a certain XML base. If you are new to XML, I suggest you continue reading this article, first, let's take a look at the materials such as "What is XML" and "Start with XML.

Introduction to xmltextwriter objects:

The xmltextwriter object contains many methods that can be used to add elements and attributes to an XML file when creating an XML file. The following are important:

Writestartdocument ()-This method is used to create an XML file first. It is the first line of code used to create an XML file. It is used to specify the file as an XML file and set its encoding type;

Writestartelement (string)-This method is used to create new elements in the XML file. You can set the element name through the string parameter (of course, you can also use the optional keyword to specify an optional parameter );

Writeelementstring (name, text_value)-You can use this method to create an element that has nothing but characters (such as no nested elements;

Writeendelement ()-corresponding to the writestartelement (string) method, as the end of an element;

Writeenddocument ()-after the XML file is created, use this method to complete the process;

Close ()-close all text streams and output the created XML file to the specified position.

To create an XML file using the xmltextwriter object, you must specify the file type in the class constructor and the encoding type must be system. text. encoding, such as: system. text. encoding. ASCII, system. text. encoding. unicode and system. text. encoding. utf8: specify the type in the xmltextwriter class constructor, and output the XML file in the form of the stream file.

Create a simple XML file using the xmltextwriter object

Next, we will demonstrate how to use the xmltextwriter object to create a simple XML document and save it to a specified location. This XML file will contain information about the users accessing the file, the output format is as follows:

<Userinfo>
<Browserinfo>
<Urlreferrer> URL referrer info </urlreferrer>
<Useragent> User Agent referrer info </useragent>
<Userages> ages info </userages>
</Browserinfo>
<Visitinfo timevisited = "date/time the page was visited">
<Ip> visitor's IP address </IP>
<Rawurl> raw URL requested </rawurl>
</Visitinfo>
</Userinfo>

This XML file with this structure is used as the output object, so that all previously mentioned methods can be used here for convenience.

The following is the ASP. NET Code required to create the XML file:

<% @ Import namespace = "system. xml" %>
<% @ Import namespace = "system. Text" %>
<Script language = "C #" runat = "server">
Void page_load (Object sender, eventargs E)
{
// Create a new xmltextwriter instance
Xmltextwriter writer = new
Xmltextwriter (server. mappath ("userinfo. xml"), encoding. utf8 );

// Start writing!
Writer. writestartdocument ();
Writer. writestartelement ("userinfo ");

// Creating the <browserinfo> element
Writer. writestartelement ("browserinfo ");

If (request. urlreferrer = NULL)
Writer. writeelementstring ("urlreferrer", "NONE ");
Else
Writer. writeelementstring ("urlreferrer ",
Request. urlreferrer. pathandquery );

Writer. writeelementstring ("useragent", request. useragent );
Writer. writeelementstring ("userages ",
String. Join (",", request. userages ));
Writer. writeendelement ();

// Creating the <visitinfo> element
Writer. writestartelement ("visitinfo ");
Writer. writeattributestring ("timevisited", datetime. Now. tostring ());
Writer. writeelementstring ("ip", request. userhostaddress );
Writer. writeelementstring ("rawurl", request. rawurl );
Writer. writeendelement ();

Writer. writeendelement ();
Writer. writeenddocument ();
Writer. Close ();
}

First, check whether the system has been imported. XML and system. text namespace. Then, create an xmltextwriter object instance in the page_load event, and save the created XML file as userinfo. the XML file and Its Encoding type are utf8 (a translation of 16-bit Unicode encoding into 8-bits), and then the writestartelement (elementname) method is used to create elements nested with other elements, it ends with writeendelement (). In addition, we use the writeelementstring (elementname, textvalue) method to create elements with no nested other elements.

Output XML file in browser window

The previous example demonstrates how to use the xmltextwriter object to create an XML file and save it as a file. This file may be what you need, but sometimes, we need to display the created XML file in the browser. At this time, we can use the above sample code to create userinfo. XML file, open it, and then use response. write () output it, but this method is not very good.

A good method is to immediately display the result of the xmltextwriter object in the browser. To implement this function, you only need to modify a line of code on the basis of the Code in the preceding example, in the class constructor of xmltextwriter, we do not specify a file path, but response. outputstream to enable ASP.. Net Program directly outputs XML to the browser, instead of saving it as a file. Of course, you can also set <@ page...> the MIME type in the command is text/XML to implement the same function, but I suggest you do not use this method, some browsers interpret the format as HTML because it contains all XML elements and deletes all spaces ).

The modified code is listed in bold as follows:

<@ Page contenttype = "text/XML" %>
<% @ Import namespace = "system. xml" %>
<% @ Import namespace = "system. Text" %>
<Script language = "C #" runat = "server">
Void page_load (Object sender, eventargs E)
{
// Create a new xmltextwriter instance
Xmltextwriter writer = new
Xmltextwriter (response. outputstream, encoding. utf8 );

// Start writing!
...
}

Note: although you are accessing the Asp.net web page, you can only view the XML document for this instance. This document is the same as the XML file created earlier, previously, it was saved as an XML file userinfo. XML.

Summary

This article demonstrates.. NET Framework. XML. xmltextwriter class to create an XML file. The xmltextwriter object can create an XML file and save it to the specified location. It can also be directly displayed in the browser as a specified stream, in a lot of coding work, using xmltextwriter object to build XML-based programs has many advantages, mainly including making the code more concise and readable, do not worry about whether the output XML file complies with the specifications.

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.