XmlTextWriter create an XML file

Source: Internet
Author: User
Tags format object contains end net readable string
xml| Create

Introduction

With the popularization of XML and the large number of applications in Dynamic Web applications, how to pass. NET creation, deletion, and modification of XML files are also important. A simple concept is that an XML file is no different from a large text file, and it is preceded by. NET appears, many ASP developers, when he needs the program output XML file, usually is the Response.Write () method output as an XML document.

Using Response.Write () to output XML documents is not such a good method, first of all, when we use this method to output word specifier to form an XML file, we are very worried that the output of these characters is not in accordance with the XML specification, XML documents that do not conform to the XML specification will not be fully displayed, such as <,>,& "", And ' These symbols, when they appear in the XML file, we have to manually look up these irregular characters; again, use response when we need to output an XML file that contains a lot of namespaces, attributes, and elements. The code required by the Write () method will become verbose and less readable.

Fortunately, the. NET Framework provides a class-system.xml.xmltextwriter specifically for creating XML files, using this class to create XML files, and you don't have to worry about whether the output conforms to the XML spec problem, And the code will become very concise. In this article, we'll delve into how to use the XmlTextWriter class to create an XML file.

A description of XML

This article assumes that the reader has a certain XML base, and if you have just contacted XML, I suggest that you go ahead and look at "What is XML" and "XML start" before you continue reading this article.


Introduction to XmlTextWriter objects:

The XmlTextWriter object contains a number of methods that you can use to add elements and attributes to an XML file when you create an XML file, more importantly:

WriteStartDocument ()-this method is first needed to create an XML file, which is the first line of code to create an XML file that specifies that the file is an XML file and sets its encoding type;

WriteStartElement (String)-the effect of this method is to create a new element in an XML file, you can set the name of the element by using the string argument (of course, you can also use the optional keyword to specify an optional argument);

WriteElementString (name, Text_value)-You can use this method if you need to create an element that has nothing but characters (such as a nested element);

WriteEndElement ()-Corresponds to the WriteStartElement (string) method as the end of an element;

WriteEndDocument ()-xml the end of the file after the creation is complete;

Close ()-Closes all text streams, outputting the created XML file to the specified location.

Creating an XML file using the XmlTextWriter object requires specifying the type of the file in the Class builder, and the encoding type must be System.Text.Encoding, such as: System.Text.Encoding.ASCII, System.Text.Encoding.Unicode and System.Text.Encoding.UTF8, in the XmlTextWriter class constructor, specify the type of the output XML file that will be output in the form of that stream file.

Create a simple XML file using the XmlTextWriter object

Next, let's demonstrate how to use the XmlTextWriter object to create a simple XML document and save it to a specified location, which will contain information about the user accessing the file, and its output format is as follows:




URL Referrer Info
User Agent Referrer Info
Languages Info


visitor ' s IP address
Raw URL Requested

Choose this XML file with this structure as the output object, so that you can use all the previously discussed methods here to facilitate elaboration.
The following is the ASP.net code required to create the XML file:

<%@ Import namespace= "System.Xml"%>
<%@ Import namespace= "System.Text"%>

Start writing!
Writer. WriteStartDocument ();
Writer. WriteStartElement ("UserInfo");

Creating the 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 ("UserLanguages",
String.Join (",", request.userlanguages));
Writer. WriteEndElement ();

Creating the 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 we need to be aware of the import System.Xml and System.Text namespaces, and then we create a XmlTextWriter object instance in the Page_Load event, and specifies that the XML file created is saved as a userinfo.xml file and its encoding type is UTF8 (a translation of 16-bit Unicode encoding into 8-bits), and then use WriteStartElement (ElementName) method to create elements that nest other elements and end with WriteEndElement (), in addition, we use WriteElementString (ElementName, TextValue) method to create an element at the bottom that does not have nested other elements.

To output an XML file in a browser window

The previous example demonstrates how to use the XmlTextWriter object to create an XML file and save it as a file, which may be what you need, but sometimes we need to display the XML file created in the browser. We can use the example code to create the Userinfo.xml file, and then open it, then use Response.Write () to output it, but this method is not very good.

A good way is to immediately put the results of the XmlTextWriter object on the browser, to achieve this function is very easy, only to be in the code based on the example to modify a line of code, in the XmlTextWriter class builder, we do not specify as a file path, Instead, it is specified as Response.outputstream so that the ASP.net program directly outputs the XML stream to the browser instead of saving it as a file, and of course you can also set <@ Page ... > The MIME type in the directive is text/xml to achieve the same function, but I recommend that you do not use this method, because some browsers do not recognize the format and interpret it as HTML (it will contain all the XML elements and delete all the spaces).

The following is a list of some of the code that has been modified in the previous example, and the modified code shows some bold:

<@ Page contenttype= "Text/xml"%>
<%@ Import namespace= "System.Xml"%>
<%@ Import namespace= "System.Text"%>

Start writing!
...
}


Note that although you are visiting the ASP.net web page, you see the instance as just an XML document, which is the same as the XML file you created earlier, except that it was previously saved as an XML file Userinfo.xml.

Summarize

This article demonstrates how to. NET How to create an XML file using the System.Xml.XmlTextWriter class in the framework, the XmlTextWriter object can create an XML file and save it to a specified location, or it can be displayed directly in the browser as a specified stream, using XMLT in many coding efforts The Extwriter object constructs an xml-based program that has many advantages, including the need to make the code simpler and more readable without worrying about whether the output XML file conforms to the specification.



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.