C # How to create an XML file

Source: Internet
Author: User

From: http://erikfeng.cnblogs.com/archive/2005/12/26/304537.aspx
Introduction

With XML Popularity and Web ApplicationProgramHow to Use . Net Create, delete, and modify XML File changes are also important. A simple concept is, XML There is no difference between a file and a large text file, and it is prior . Net Appears, many ASP Developers, when they need program output XML Usually Response. Write () Method output is XML Documentation.
Use Response. Write () Method to output XML Document is not a good method. First, we use this method to output characters to form XML File, we will be very worried about whether the output of these characters match XML Specification, not compliant XML Standardized XML The document cannot be displayed completely, for example: < , > ,&"", And ' These symbols when they are in XML When a file appears, we must manually search for these nonstandard characters. Again, when we need to output a file that contains many namespaces, attributes, and elements XML Use Response. Write () RequiredCodeIt will become lengthy and less readable.

Fortunately,. NET FrameworkProvides a specialXMLClass used by the file-System. xml. xmltextwriter,Use this class to createXMLFile, you do not need to worry about whether the output meetsXMLWhile the Code will become very concise. In this articleArticle, We will explain in depth how to useXmltextwriterClass to createXMLFile. 
AboutXMLDescription

This article assumes that the reader hasXMLIf you are newXMLBefore reading this article, I suggest you read it first."What isXML"And"XMLStart"These materials.

XmltextwriterObject introduction:

XmltextwriterThe object contains manyXMLAdd elements and attributesXMLThe methods in the file are as follows:

Writestartdocument ()-CreateXMLThis method is used to create a file.XMLThe first line of code of the file, used to specify that the file isXMLFile and set its encoding type;

Writestartelement (string)-The role of this method isXMLFile to create new elements, you can useStringParameter Setting element name (of course, you can also useOptionalKeyword to specify an optional parameter );

Writeelementstring (name, text_value)-You can use this method to create an element without any characters (for example, no nested element;

Writeendelement ()-CorrespondingWritestartelement (string)Method, as the end of an element;

Writeenddocument ()-XMLUse this method to end after the file is created;

Close ()-Close all text streams and set the createdXMLFile output to the specified location.

UseXmltextwriterObject CreationXMLFile, you must specify the file type in the class constructor, And the encoding type must beSystem. Text. EncodingSuch:System. Text. encoding. ASCII, system. Text. encoding. UnicodeAndSystem. Text. encoding. utf8, InXmltextwriterClass constructor specifies the type in the outputXMLThe file will be output as a stream file.

UseXmltextwriterObject To create a simpleXMLFile

Next, let's demonstrate how to useXmltextwriterObject To create a simpleXMLAnd save it to the specified location.XMLThe file will contain information about the user accessing the file. Its 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 >

Choose this one with this structureXMLThe file is the output object, so that you can use all the methods mentioned previously for convenience.

CreateXMLFileASP. NETCode:

<% @ 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<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<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 there is any importSystem. xml and system. TextNamespace, And then wePage_loadCreateXmltextwriterObject instance, and specify the createdXMLSaveUserinfo. xmlFile and Its Encoding type isUtf8(A translation of 16-bit Unicode encoding into 8-bits), And then useWritestartelement (elementname)To create elements nested with other elements, andWriteendelement ()In addition, we useWriteelementstring (elementname, textvalue)Method To create an element that does not nest other elements.

Output in the browser windowXMLFile

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

A good way is to immediatelyXmltextwriterThe result of the object is displayed 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.XmltextwriterIn the class constructor, we do not specify a file path, but specifyResponse. outputstreamTo enableASP. NETProgram direct outputXMLStream to the browser, instead of saving it as a file. Of course, you can also set <@ Page...> CommandsMimeType:Text/XMLTo implement the same function, but I suggest you do not use this method, because some browsers do not recognize the format and treat itHtml(It will contain allXMLAnd delete 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 that even if you accessAsp.net WebPage, but all you can see isXMLDocument.XMLThe file is the same. The difference is that the previous file is saved asXMLFileUserinfo. xml.

Summary

This article demonstrates how. NET FrameworkHow to UseSystem. xml. xmltextwriterClass to createXMLFile,XmltextwriterYou can create an objectXMLFile and save it to the specified location. You can also directly display it in the browser as a specified stream.XmltextwriterObject Construction Based onXMLThe program has many advantages, the main of which can make the code more concise, more readable, and do not have to worry about outputXMLDocument compliance.

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.