
一、在C#程序中,创建、写入、读取XML文件的方法
1、创建和读取XML文件的方法,Values为需要写入的值
private void WriteXML(string Values)
{
//保存的XML的地址
string XMLPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\" + "文件的名称.xml";
XmlDocument xmlDoc = new XmlDocument(); //引入using System.Xml 命名空间 //创建类型声明
xmlDoc = new XmlDocument();
XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
xmlDoc.AppendChild(node);
//创建父节点
XmlNode root = xmlDoc.CreateElement("父节点");
xmlDoc.AppendChild(root);
//创建子节点,写入值
node = xmlDoc.CreateNode(XmlNodeType.Element, "子节点", null);
node.InnerText = Values;
root.AppendChild(node);
xmlDoc.Save(XMLPath);
}
2、读取XML文件中存入的值方法
private void ReadXML()
{
XmlDocument xmlDoc = new XmlDocument();
string XMLPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\" + "文件的名称.xml";
//如果文件存在
if (File.Exists(XMLPath))
{
xmlDoc.Load(XMLPath); //从指定的URL加载XML文档
XmlNode Values= xmlDoc.SelectSingleNode("父节点").SelectSingleNode("子节点");
string str= Values.InnerText; //获取到存入的值为 string
}
}