C# 读写xml文档
一、简述
记--简单的读写xml文档数据。键值对数据,与json数据类似。
二、效果
第一次运行,test.xml还没有存在,就创建test.xml,并写一些数据进去,然后第二次运行的时候将数据读取出来。
文件数据:
三、工程结构
四、源文件
Program.cs文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
namespace TestXml
{
class Program
{
static void Main(string[] args)
{
XmlDocument xmlDocument = new XmlDocument();
if (!File.Exists("D:\\Test\\test.xml"))//不存在就创建
{
//创建xml文档描述头
XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", "yes");
xmlDocument.AppendChild(xmlDeclaration);
//创建根节点1
XmlElement root1Element = xmlDocument.CreateElement("Root1");
xmlDocument.AppendChild(root1Element);
//创建根节点1的子节点数据
XmlElement wordXmlElement = xmlDocument.CreateElement("Word");
wordXmlElement.SetAttribute("单词", "love");
wordXmlElement.SetAttribute("音标", "辣褔");
wordXmlElement.SetAttribute("释义", "喜欢");
root1Element.AppendChild(wordXmlElement);//添加到根节点1
//创建根节点1的子节点数据
XmlElement stuXmlElement = xmlDocument.CreateElement("Student");
stuXmlElement.SetAttribute("学号", "20190804");
stuXmlElement.SetAttribute("姓名", "Liang");
stuXmlElement.SetAttribute("年龄", "age");
root1Element.AppendChild(stuXmlElement);//添加到根节点1
xmlDocument.Save("D:\\Test\\test.xml");//保存
Console.WriteLine("首次初始化。");
}
else //存在就将数据读取出来
{
xmlDocument.Load(@"D:\Test\test.xml");
XmlElement xmlElement = xmlDocument.DocumentElement;
XmlNodeList xmlNodeList = xmlElement.ChildNodes;//获取子节点集合
foreach (XmlNode node in xmlNodeList)//遍历子节点集合,根据Key获取Value
{
if (node.Name == "Word")
{
Console.WriteLine("单词:" + node.Attributes["单词"].Value + "\t" + "音标:" + node.Attributes["音标"].Value + "\t" + "释义:" + node.Attributes["释义"].Value);
}
else if (node.Name == "Student")
{
Console.WriteLine("学号:" + node.Attributes["学号"].Value + "\t" + "姓名:" + node.Attributes["姓名"].Value + "\t" + "年龄:" + node.Attributes["年龄"].Value);
}
}
//增加
XmlElement addXmlElement = xmlDocument.CreateElement("Word");
addXmlElement.SetAttribute("单词", "Add");
addXmlElement.SetAttribute("音标", "爱的");
addXmlElement.SetAttribute("释义", "增加");
xmlElement.AppendChild(addXmlElement);
//修改
foreach (XmlNode node in xmlNodeList)//遍历子节点集合,根据Key获取Value
{
if (node.Name == "Student" && node.Attributes["姓名"].Value == "Liang")
{
node.Attributes["学号"].Value = "20190808";
}
}
//删除
foreach (XmlNode node in xmlNodeList)//遍历子节点集合,根据Key获取Value
{
if (node.Name == "Word" && node.Attributes["单词"].Value == "love")
{
xmlElement.RemoveChild(node);
}
}
xmlDocument.Save("D:\\Test\\test.xml");//保存
}
Console.ReadKey();//等待输入
}
}
}
五、待添加