实现XML文件的创建,子元素的添加,修改,删除。
引用
using System.Xml;
实现方法如下:
创建XML文件方法
static void CreateXMLFile()
{
XmlDocument xdoc = new XmlDocument();
XmlElement root = xdoc.CreateElement("MOVIES");
xdoc.AppendChild(root);
Console.WriteLine(xdoc.InnerXml);
xdoc.Save("movies.xml");//可以指定存储路径
}
添加元素方法:
static void AddRecordToXML()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load("movies.xml");
XmlNode root = xdoc.SelectSingleNode("MOVIES");
XmlElement movie = xdoc.CreateElement("MOVIE");
root.AppendChild(movie);
XmlAttribute id = xdoc.CreateAttribute("Id");
id.Value = xdoc.SelectNodes("MOVIES/MOVIE").Count.ToString(); //"1";
movie.Attributes.Append(id);
XmlElement title = xdoc.CreateElement("Title");
title.InnerText = "The Godfather";
movie.AppendChild(title);
Console.WriteLine(xdoc.InnerXml);
xdoc.Save("movies.xml");
}
读取元素方法:
static void ReadRecords()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load("movies.xml");
XmlNodeList nodes = xdoc.SelectNodes("MOVIES/MOVIE");
foreach (XmlNode node in nodes)
{
//Console.WriteLine(node.Attributes[0].Value);
//Console.WriteLine(node.ChildNodes[0].InnerText);
Console.WriteLine($"{node.Attributes[0].Value} {node.ChildNodes[0].InnerText}");
}
}
更新元素方法:
static void UpdateRecords()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load("movies.xml");
XmlNode tgNode = xdoc.SelectSingleNode("MOVIES/MOVIE[@Id=1]/Title");
tgNode.InnerText = "Goodfellas";
Console.WriteLine(xdoc.InnerXml);
xdoc.Save("movies.xml");//可以指定存储路径
}
删除元素方法:
static void DeleteRecords()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load("movies.xml");
Console.WriteLine($"File Load ...: {xdoc.InnerXml}");
var root = xdoc.SelectSingleNode("MOVIES");
Console.WriteLine($"Root Node: {root.InnerXml}");
var tgNode = root.SelectSingleNode("MOVIE[Title='Lord of the Rings']"); //xdoc.SelectSingleNode("MOVIES/MOVIE");
Console.WriteLine($"Target Node:{tgNode.InnerXml}");
var tgNode2 = root.SelectSingleNode("MOVIE[@Id=3]");
Console.WriteLine($"Target Node2:{tgNode2.InnerXml}");
root.RemoveChild(tgNode2);
Console.WriteLine("\n======================\n");
Console.WriteLine($"Child Node deleted: {xdoc.InnerXml}");
xdoc.Save("movies.xml");
}
测试方法:
static void Main(string[] args)
{
CreateXMLFile();
AddRecordToXML();
ReadRecords();
UpdateRecords();
DeleteRecords();
Console.Read();
}
网友评论