C# create xml file, with example of generating a website error log

Lionsure 2020-08-26 Original by the website

For files with little content, saving with xml is also optional. For example, the configuration information of software and website, program operation log, etc. can all be saved in xml file. The file is not large, which is convenient for processing and does not affect the execution speed of program; it does not require third-party support and is easy to transplant.

XML files are generally generated dynamically by programs, so to use it, you must know how to generate xml files with programs. This article will discuss two methods for C# to generate xml files, one is without attributes, and the other is with attributes to meet various needs in the development process. How to create xml file in c# with example?

 

1. C# create xml file(without attributes)

This example introduces the common C# xml file creation method, and only generates the xml file of two-level nodes. It can be used to record website operation error information, website and software configuration information, etc. in actual development. The code is as follows (an example of creating a program error log):

using System.IO;
       using System.Xml;

private string filePath = @"G:\xq\test\log.xml";

/// <summary>
       /// C# build xml document
       /// </summary>

       private void CreateXmlFile()
       {
              try
              {
                     FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
                     StreamWriter sw = new StreamWriter(fs);

              sw.BaseStream.Seek(0, SeekOrigin.End);
                     sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
                     sw.WriteLine("<Logs>");
                     sw.WriteLine("</Logs>");

              sw.Flush();
                     sw.Close();
                     fs.Close();
              }
              catch(Exception ex)
              {
                     throw new ArgumentNullException(ex.Message);
              }
       }

/// <summary>
       ///  Example of C# create xml file for program error log
       /// </summary>
       /// <param name="ex">Exception</param>

       public void CreateLogs(Exception ex)
       {
              CreateXmlFile();
              XmlDocument xDoc = new XmlDocument();
              xDoc.Load(filePath);

       XmlNodeList xnl = xDoc.SelectNodes("Logs/Log");
              XmlNode rootNode = xDoc.SelectSingleNode("//Logs");

       //Create nodes
              XmlNode xnLog = xDoc.CreateNode("element", "Log", "");
              XmlNode xnLogDate = xDoc.CreateNode("element", "LogDate", "");//Date
              XmlNode xnMessage = xDoc.CreateNode("element", "Message", "");//Error message
              XmlNode xnSource = xDoc.CreateNode("element", "Source", "");//Error source
              XmlNode xnStack = xDoc.CreateNode("element", "Stack", "");//Stack contents
              XmlNode xnTargetSite = xDoc.CreateNode("element", "TargetSite", "");//The method that raised the exception
              XmlNode xnRawUrl = xDoc.CreateNode("element", "RawUrl", "");//Error page

       //Add data
              xnLogDate.InnerText = DateTime.Now.ToString();
              xnMessage.InnerText = ex.Message;
              xnSource.InnerText = ex.Source.ToString();
              xnStack.InnerText = ex.StackTrace.ToString();
              xnTargetSite.InnerText = ex.TargetSite.ToString();
              xnRawUrl.InnerText = HttpContext.Current.Request.Url.PathAndQuery.ToString();

       xnLog.AppendChild(xnLogDate);
              xnLog.AppendChild(xnMessage);
              xnLog.AppendChild(xnSource);
              xnLog.AppendChild(xnStack);
              xnLog.AppendChild(xnTargetSite);
              xnLog.AppendChild(xnRawUrl);

       rootNode.AppendChild(xnLog);
              try
              {
                     xDoc.Save(filePath);
              }
              catch (Exception e)
              {
                     throw new ArgumentNullException(e.Message);
              }
       }

Call:

Exception ex = Server.GetLastError().GetBaseException();
       CreateLogs(ex);

 

 

2. C# create xml file(with attributes)

This example introduces the method of generating nodes with attributes from C# xml files, creating xml files of three-level nodes, and so on for more levels. Code show as below:

/// <summary>
       /// C# create xml file with attributes
       /// </summary>

       private void CreateXmlWithAttribute()
       {
              CreateXmlFile();
              XmlDocument xDoc = new XmlDocument();
              XmlNode rootNode = xDoc.SelectSingleNode("//Logs");

       //Primary node
              XmlElement xeLog = xDoc.CreateElement("Log");
              xeLog.SetAttribute("id", "1");//Set Attribute

       //Secondary node
              XmlElement xeSe = xDoc.CreateElement("se");
              xeSe.SetAttribute("id", "1-1");
              xeSe.SetAttribute("value", "Secondary node");

       //Tertiary node
              XmlElement xeTh = xDoc.CreateElement("th");
              xeTh.InnerText = "Tertiary node";
              xeSe.AppendChild(xeTh);

       xeLog.AppendChild(xeSe);
              rootNode.AppendChild(xeLog);
       }