操作XML文件需要引用命名空间:System.Xml;
向Xml文件中添加信息
添加Student.xml文件,文件信息如下:
<?xml version="1.0" encoding="utf-8"?>
<Students>
<Student class="一班">
<Name>张三</Name>
<Gender>男</Gender>
<Age>19</Age>
</Student>
<Student class="二班">
<Name>李四</Name>
<Gedner>女</Gedner>
<Age>20</Age>
<Name>had</Name>
<Gender>女</Gender>
<Age>16</Age>
</Students>
代码:
XmlDocument doc = new XmlDocument();
//修改.exe文件夹下的Student.xml,需要单机程序中的Student.xml文件将其“复制到输出目录”属性,修改为“始终复制”
//string exePath = Application.StartupPath+"\\Student.xml";
//doc.Load(exePath);
//将程序目录下的Student.Xml中添加学生信息。
String exePath = Application.StartupPath;
int idx = exePath.LastIndexOf("bin");
exePath = exePath.Substring(0, idx) + "Student.xml";
doc.Load(exePath);
XmlNode node = doc.CreateNode(XmlNodeType.Element, "Student", "");
XmlAttribute attr = doc.CreateAttribute("class");
attr.Value = "一班";
node.Attributes.Append(attr);
XmlNode name = doc.CreateNode(XmlNodeType.Element, "Name","");
name.InnerText = "had";
XmlNode gender = doc.CreateNode(XmlNodeType.Element, "Gender", "");
gender.InnerText = "女";
XmlNode age = doc.CreateNode(XmlNodeType.Element, "Age", "");
age.InnerText = "16";
node.AppendChild(name);
node.AppendChild(gender);
node.AppendChild(age);
doc["Students"].AppendChild(node);
doc.Save(exePath);
删除Xml文件中的数据
XmlDocument doc = new XmlDocument();
XmlNodeList list = doc["Students"].ChildNodes;
foreach (XmlNode node in list)
{
foreach (XmlNode nd in node.ChildNodes)
{
if (nd.InnerText == "had")
{
nd.ParentNode.ParentNode.RemoveChild(nd.ParentNode);
doc.Save(exePath);
return;
}
}
}
修改xml中的数据:
XmlDocument doc = new XmlDocument();
for (int i = 0; i < list.Count; i++)
XmlNode node = list[i];
if (node["Name"].InnerText == "李四")
node["Gender"].InnerText = "男";
if (nd.InnerText == "张三")
nd.ParentNode["Gender"].InnerText = "女";
}
doc.Save(exePath);
读取xml文件的所有数据
String name = node["Name"].InnerText;
string gender = node["Gender"].InnerText;
string age = node["Age"].InnerText;
listBox1.Items.Add(name + "," + age + "," + gender);
}
创建Xml文件,并向里面添加数据
private void button1_Click(object sender, EventArgs e)
{
CreateXmlFile();
}
public void CreateXmlFile()
exePath = exePath.Substring(0, idx) + "aa.xml";
XmlDocument xmlDoc = new XmlDocument();
//创建类型声明节点
XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
xmlDoc.AppendChild(node);
//创建根节点
XmlNode root = xmlDoc.CreateElement("User");
xmlDoc.AppendChild(root);
CreateNode(xmlDoc, root, "name", "xuwei");
CreateNode(xmlDoc, root, "sex", "male");
CreateNode(xmlDoc, root, "age", "25");
xmlDoc.Save(exePath);
/// <summary>
/// 创建节点
/// </summary>
/// <param name="xmldoc"></param> xml文档
/// <param name="parentnode"></param>父节点
/// <param name="name"></param> 节点名
/// <param name="value"></param> 节点值
///
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);
}