The implementation method for creating and reading XML files in C
- 2020-05-19 05:31:58
- OfStack
1. Create a simple XML file
To facilitate testing, we will first create the console application. The project is named CreateXml, Program.cs and the code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace CreateXml
{
class Program
{
static void Main(string[] args)
{
Program app = new Program();
app.CreateXmlFile();
}
public void CreateXmlFile()
{
XmlDocument xmlDoc = new XmlDocument();
// Create a type declaration node
XmlNode node=xmlDoc.CreateXmlDeclaration("1.0","utf-8","");
xmlDoc.AppendChild(node);
// Create the root node
XmlNode root = xmlDoc.CreateElement("User");
xmlDoc.AppendChild(root);
CreateNode(xmlDoc, root, "name", "xuwei");
CreateNode(xmlDoc, root, "sex", "male");
CreateNode(xmlDoc, root, "age", "25");
try
{
xmlDoc.Save("c://data2.xml");
}
catch (Exception e)
{
// Display error message
Console.WriteLine(e.Message);
}
//Console.ReadLine();
}
/// <summary>
/// Create a node
/// </summary>
/// <param name="xmldoc"></param> xml The document
/// <param name="parentnode"></param> The parent node
/// <param name="name"></param> The node name
/// <param name="value"></param> Node values
///
public void CreateNode(XmlDocument xmlDoc,XmlNode parentNode,string name,string value)
{
XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
node.InnerText = value;
parentNode.AppendChild(node);
}
}
}
This will create the data2.xml file in the C root directory
<?xml version="1.0" encoding="utf-8"?>
<User>
<name>xuwei</name>
<sex>male</sex>
<age>25</age>
</User>
2. Create multi-node, multi-level XML files
A simple change to the CreateXmlFile() method is required, as follows:
public void CreateXmlFile()
{
XmlDocument xmlDoc = new XmlDocument();
// Create a type declaration node
XmlNode node=xmlDoc.CreateXmlDeclaration("1.0","utf-8","");
xmlDoc.AppendChild(node);
// Create the root node
XmlNode root = xmlDoc.CreateElement("Users");
xmlDoc.AppendChild(root);
XmlNode node1 = xmlDoc.CreateNode(XmlNodeType.Element, "User", null);
CreateNode(xmlDoc, node1, "name", "xuwei");
CreateNode(xmlDoc, node1, "sex", "male");
CreateNode(xmlDoc, node1, "age", "25");
root.AppendChild(node1);
XmlNode node2 = xmlDoc.CreateNode(XmlNodeType.Element, "User", null);
CreateNode(xmlDoc, node2, "name", "xiaolai");
CreateNode(xmlDoc, node2, "sex", "female");
CreateNode(xmlDoc, node2, "age", "23");
root.AppendChild(node2);
try
{
xmlDoc.Save("c://data5.xml");
}
catch (Exception e)
{
// Display error message
Console.WriteLine(e.Message);
}
//Console.ReadLine();
}
The content of the generated xml file is as follows:
<?xml version="1.0" encoding="utf-8"?>
<Users>
<User>
<name>xuwei</name>
<sex>male</sex>
<age>25</age>
</User>
<User>
<name>xiaolai</name>
<sex>female</sex>
<age>23</age>
</User>
</Users>