通过XmlWriterSettings类格式化XML文件的输出

 7_XmlWritingWithSettings.aspx


<%@ 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 id="Head1" 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>

 


总结:创建了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文 件输出的所有操作。


 

你可能感兴趣的:(Writer)