写入一个简单的XML文件

来源:互联网 发布:php如何运行 编辑:程序博客网 时间:2024/04/30 09:44

 演示了如何利用XmlWriter类的方法从ASP.NET页面写入一个简单的XML文件。执行这个操作的ASP.NET页面。

 使用XmlWriter类写入一个简单的XML文件

<%@ 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>

 

 

在浏览器中运行这个示例,将会看到如下提示:

An Exception occurred: Access to the path "C:/Data/Employees.xml" is denied.

导致这个异常,是因为用于ASP.NET工作过程的ASPNET账户没有对C:/Data目录写的权限。您可以通过 从Windows资源管理器浏览C:/Data目录并将可以写入该目录的权限赋给ASPNET账户来解决这个问题。如果您在浏览器中浏览这个页面,就会看 到“File is written successfully.”消息。从Windows资源管理器浏览C:/Data目录并查找名为Employees.xml的文件。该文件应如下所示

<?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>

乍一看,这个输出看上去并不顺眼。下一节将显示如何使用XmlWriterSettings类将这个输出格式化。现在,还是先来一步步地解释程序清单。

在程序清单4-6中的第一步是导入应用程序所需的所有类。在Page_Load()函数中,有一个名为 xmlFilePath且保存了XML文件路径的变量。随后它将声明一个using代码块来创建XmlWriter对象并传入xmlFilePath作为 参数。接下来它开始通过调用WriteStartDocument()方法来写入XML文档。这将会向文件写入XML声明。很明 显,WriteComment()方法用于将有意义的注释插入XML文件中。因为在大多数情况下这是一个很好的做法,所以如果您的XML文件广泛分布,那 么就必须编写注释。

接下来是建立XML文档的过程,您可以使用WriteStartElement()方法一个接一个地向文档中添加元 素。这个方法只需要一个参数,元素名称,所以不能用于写入包含有字符数据的元素。与WriteStartElement()方法相对的是 WriteEndElement()方法,它用于向XML文档写入相应的结束元素。请注意这里的方法调用顺序非常重要,否则您的XML输出将不会是格式良 好的。当然,写入无内容的元素是一件非常轻松的事情,但是这实际上并不是非常有用,这就是为什么还需要其他方法来向XML文件中写入数据的原因所在。

首先,WriteElementString()方法需要两个参数:元素的名称和包含其中的数据。请注意,您不需要担心以这种方式写入的关闭元素;WriteElementString()方法将为您完成所有的工作!

writer.WriteElementString("firstName", "Nancy");

XmlWriter类还提供了方便的WriteAttributeString()方法用于写入属性。例如,如下代码使用了这个方法向<employee>元素添加id属性。

writer.WriteAttributeString("id", "1");

Flush()方法整合了很多操作而直接将内存中的XML数据流写入文件。在这之后是一个catch块,用于捕捉错误并以适当的方式退出try代码块。

6. 格式化XmlWriter的输出
正如您现在所体会到的,使用XmlWriter对象非常简单。介绍性的示例为您演示了如何使用XmlWriter类写入XML文件而无需太多麻烦。在本节 中,您将会更加深入地了解如何通过XmlWriterSettings类的方法来格式化XML文件的输出。在介绍示例之前,先看看 XmlWriterSettings类的属性和方法。表4-9列出了XmlWriterSettings对象的重要属性。

表4-9 XmlWriterSettings类的重要属性

属    性
说    明

CheckCharacters
获得或者设置用来指示是否要执行字符检查的值

Encoding
获得或者设置以Encoding对象的形式使用的文本编码

Indent
获得或者设置用来指示是否缩排元素的布尔值

IndentChars
获得或者设置在缩排时使用的字符串

NewLineChars
获得或者设置用于换行的字符串

NewLineOnAttributes
获得或者设置用于指示属性是否写入新行的布尔值

OmitXmlDeclaration
获得或者设置用于指示是否应该写入XML声明的布尔值

除了表4-9中显示的属性之外,XmlWriterSettings对象还包含了同样由 XmlReaderSettings对象支持的属性,如ConformanceLevel,并且这些属性都具有相同的作用。程序清单4-7显示了如何利用 XmlWriterSettings类来定制由XmlWriter对象创建的XML文件的输出。

程序清单4-7 通过XmlWriterSettings类格式化XML文件的输出

   <%@ 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>

下面是由程序清单4-7生成的输出。

<?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>

现在我们来详细查看一下对程序清单4-6作出的修改所带来的令人惊讶的格式。首先,创建了 XmlWriterSettings对象的一个实例,然后设置各种属性,如Indent、ConformanceLevel、IndentChars和 OmitXmlDeclaration。

XmlWriterSettings settings = new XmlWriterSettings();

settings.Indent = true;

settings.ConformanceLevel = ConformanceLevel.Auto;

settings.IndentChars = "/t";

settings.OmitXmlDeclaration = false;

然后将XmlWriterSettings对象作为一个参数传入XmlWriter对象的Create()方法中, 并将XmlWriterSettings对象的设置应用于新创建的XmlWriter对象。以上就是利用XmlWriterSettings对象来控制由 XmlWriter对象创建的XML文件输出的所有操作。