Demonstrate how to use the xmlwriter class to write a simple XML file from an ASP. NET page. ASP. NET page for this operation.
Write a simple XML file using the xmlwriter class
<% @ Page Language = "C #" %>
<% @ Import namespace = "system. xml" %>
<SCRIPT runat = "server">
Void page_load (Object sender, eventargs E)
{
String xmlfilepath = @ "C:/data/employees. xml ";
Try
{
Using (xmlwriter writer = xmlwriter. Create (xmlfilepath ))
{
// Start writing the XML document
Writer. writestartdocument (false );
Writer. writecomment ("This XML file represents the details of" +
"An employee ");
// Start with the root element
Writer. writestartelement ("employees ");
Writer. writestartelement ("employee ");
Writer. writeattributestring ("ID", "1 ");
Writer. writestartelement ("name ");
Writer. writeelementstring ("firstname", "Nancy ");
Writer. writeelementstring ("lastname", "lastname ");
Writer. writeendelement ();
Writer. writeelementstring ("city", "Seattle ");
Writer. writeelementstring ("State", "wa ");
Writer. writeelementstring ("zipcode", "98122 ");
Writer. writeendelement ();
Writer. writeendelement ();
Writer. writeenddocument ();
// Flush the object and write the XML data to the file
Writer. Flush ();
Lblresult. Text = "file is written successfully ";
}
}
Catch (exception ex)
{
Lblresult. Text = "An exception occurred:" + ex. message;
}
}
</SCRIPT>
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> writing XML file </title>
</Head>
<Body>
<Form ID = "form1" runat = "server">
<Div>
<Asp: Label id = "lblresult" runat = "server"/>
</Div>
</Form>
</Body>
</Html>
Run this example in the browser and you will see the following prompt:
An exception occurred: access to the path "C:/data/employees. xml" is denied.
This exception occurs because the ASPNET account used for ASP. NET workflow has no permission to write to the C:/data directory. You can solve this problem by browsing the C:/data directory from Windows Resource Manager and assigning the permission to write to the directory to the ASPNET account. If you browse this page in your browser, you will see the message "file is written successfully. View the C:/data directory in Windows Resource Manager and find the file named employees. xml. The file should be as follows.
<? XML version = "1.0" encoding = "UTF-8" standalone = "no"?>
<! -- This XML file represents the details of an employee -->
<Employees>
<Employee ID = "1">
<Name>
<Firstname> Nancy </firstname>
<Lastname> lastname </lastname>
</Name>
<City> Seattle </city>
<State> wa </State>
<Zipcode> 98122 </zipcode>
</Employee>
</Employees>
At first glance, this output does not look pleasing to the eye. The next section shows how to format the output using the xmlwritersettings class. Now, let's explain the program list step by step.
The first step in program listing 4-6 is to import all classes required by the application. In the page_load () function, there is a variable named xmlfilepath that stores the XML file path. Then it will declare a using code block to create the xmlwriter object and pass in the xmlfilepath as the parameter. Next, it starts to write the XML document by calling the writestartdocument () method. This will write an XML declaration to the file. Obviously, the writecomment () method is used to insert meaningful comments into the XML file. This is a good practice in most cases, so if your xml files are widely distributed, you must write comments.
The next step is to create an XML document. You can use the writestartelement () method to add Canadian element to the document one by one. This method only requires one parameter and element name, so it cannot be used to write elements containing character data. Compared with the writestartelement () method, the writeendelement () method is used to write the corresponding end element to the XML document. Note that the method calling sequence here is very important, otherwise your XML output will not be in a good format. Of course, writing content-free elements is a very easy task, but it is not actually very useful, this is why other methods are required to write data to the XML file.
First, the writeelementstring () method requires two parameters: the name of the element and the data contained in it. Please note that you do not need to worry about writing close elements in this way; The writeelementstring () method will complete all the work for you!
Writer. writeelementstring ("firstname", "Nancy ");
The xmlwriter class also provides a convenient writeattributestring () method for writing attributes. For example, the following code uses this method to add the ID attribute to the <employee> element.
Writer. writeattributestring ("ID", "1 ");
The flush () method integrates many operations and directly writes XML data streams in the memory to files. After that, a catch block is used to capture errors and exit the try code block in an appropriate way.
6. format the output of xmlwriter
As you have learned, using xmlwriter objects is very simple. The introductory example shows how to use the xmlwriter class to write XML files without much trouble. In this section, you will learn more about how to format the output of an XML file through the xmlwritersettings class. Before introducing the example, let's take a look at the attributes and methods of the xmlwritersettings class. Table 4-9 lists the important attributes of the xmlwritersettings object.
Table 4-9 important attributes of the xmlwritersettings class
Genus
Description
Checkcharacters
Obtains or sets the value to indicate whether to perform a character check.
Encoding
Obtains or sets the text encoding used in the form of an encoding object.
Indent
Obtain or set a Boolean value that indicates whether to shrink an element.
Indentchars
Obtain or set the string used for contraction.
Newlinechars
Obtains or sets the string used for line feed.
Newlineonattributes
Obtain or set a Boolean value that indicates whether the attribute is written to a new row.
Omitxmldeclaration
Obtain or set a Boolean value that indicates whether the XML declaration should be written.
In addition to the attributes displayed in table 4-9, the xmlwritersettings object also contains attributes that are also supported by the xmlreadersettings object, such as conformancelevel, and these attributes have the same effect. Listing 4-7 shows how to use the xmlwritersettings class to customize the output of the XML file created by the xmlwriter object.
Program list 4-7 use the xmlwritersettings class to format the output of an XML file
<% @ Page Language = "C #" %>
<% @ Import namespace = "system. xml" %>
<SCRIPT runat = "server">
Void page_load (Object sender, eventargs E)
{
String xmlfilepath = @ "C:/data/employees. xml ";
Try
{
Xmlwritersettings settings = new xmlwritersettings ();
Settings. indent = true;
Settings. conformancelevel = conformancelevel. Auto;
Settings. indentchars = "/t ";
Settings. omitxmldeclaration = false;
Using (xmlwriter writer = xmlwriter. Create (xmlfilepath, settings ))
{
// Start writing the XML document
Writer. writestartdocument (false );
// Start with the root element
Writer. writestartelement ("employees ");
Writer. writestartelement ("employee ");
Writer. writeattributestring ("ID", "1 ");
Writer. writestartelement ("name ");
Writer. writeelementstring ("firstname", "Nancy ");
Writer. writeelementstring ("lastname", "lastname ");
Writer. writeendelement ();
Writer. writeelementstring ("city", "Seattle ");
Writer. writeelementstring ("State", "wa ");
Writer. writeelementstring ("zipcode", "98122 ");
Writer. writeendelement ();
Writer. writeendelement ();
Writer. writeenddocument ();
// Flush the object and write the XML data to the file
Writer. Flush ();
Lblresult. Text = "file is written successfully ";
}
}
Catch (exception ex)
{
Lblresult. Text = "An exception occurred:" + ex. message;
}
}
</SCRIPT>
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> writing XML file with xmlwritersettings </title>
</Head>
<Body>
<Form ID = "form1" runat = "server">
<Div>
<Asp: Label id = "lblresult" runat = "server"/>
</Div>
</Form>
</Body>
</Html>
The following is the output generated by listing 4-7 of the program.
<? XML version = "1.0" encoding = "UTF-8" standalone = "no"?>
<Employees>
<Employee ID = "1">
<Name>
<Firstname> Nancy </firstname>
<Lastname> lastname </lastname>
</Name>
<City> Seattle </city>
<State> wa </State>
<Zipcode> 98122 </zipcode>
</Employee>
</Employees>
Now let's take a closer look at the surprising format of the changes made to the program list 4-6. First, an instance of the xmlwritersettings object is created, and various attributes are set, such as indent, conformancelevel, indentchars, and omitxmldeclaration.
Xmlwritersettings settings = new xmlwritersettings ();
Settings. indent = true;
Settings. conformancelevel = conformancelevel. Auto;
Settings. indentchars = "/t ";
Settings. omitxmldeclaration = false;
The xmlwritersettings object is passed into the CREATE () method of the xmlwriter object as a parameter, and the settings of the xmlwritersettings object are applied to the newly created xmlwriter object. The above describes how to use the xmlwritersettings object to control all the operations output by the XML file created by the xmlwriter object.