void Start () {
//CreateXml();
//AddXmlNode();
//ChangeXmlNodeValue();
//ChangeXmlNode();
//DelNodeChild();
}
//1.创建XML表
private void CreateXml(){
string path = Application.dataPath + "/file.txt";
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(dec);
XmlElement root = doc.CreateElement("Employees");
doc.AppendChild(root);
XmlElement node1 = doc.CreateElement("Node");
node1.SetAttribute("ge", "嘉怡");
node1.SetAttribute("IQ", "261");
XmlElement node2 = doc.CreateElement("Title");
node2.InnerText = "历史";
node1.AppendChild(node2);
XmlElement node3 = doc.CreateElement("author");
node3.InnerText = "jiji";
node1.AppendChild(node3);
XmlElement node4 = doc.CreateElement("price");
node4.InnerText = "58.3";
node1.AppendChild(node4);
root.AppendChild(node1);
doc.Save(path);
}
//2.添加节点
private void AddXmlNode()
{
string path = Application.dataPath + "/file.txt";
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNode root = doc.SelectSingleNode("Employees");
XmlElement node1 = doc.CreateElement("Node");
node1.SetAttribute("ge", "佳璐");
node1.SetAttribute("IQ", "120");
root.AppendChild(node1);
XmlElement node2 = doc.CreateElement("Title");
node2.InnerText = "政治";
node1.AppendChild(node2);
XmlElement node3 = doc.CreateElement("author");
node3.InnerText = "KiKi";
node1.AppendChild(node3);
XmlElement node4 = doc.CreateElement("price");
node4.InnerText = "60.0";
node1.AppendChild(node4);
doc.Save(path);
}
//3.修改节点的值
private void ChangeXmlNodeValue()
{
string path = Application.dataPath + "/file.txt";
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList NodesList = doc.SelectSingleNode("Employees").ChildNodes;
foreach (XmlElement item in NodesList)
{
if (item.GetAttribute("ge") == "嘉怡")
{
item.SetAttribute("ge", "Update嘉怡");
XmlNodeList list = item.ChildNodes;
foreach (XmlElement it in list)
{
if (it.Name == "price")
{
it.InnerText = "100000";
}
}
}
}
doc.Save(path);
}
//4.修改节点
private void ChangeXmlNode()
{
string path = Application.dataPath + "/file.txt";
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList NodesList = doc.SelectSingleNode("Employees").ChildNodes;
foreach (XmlElement item in NodesList)
{
//添加节点属性
item.SetAttribute("test", "11111");
//添加节点的子节点
XmlElement it = doc.CreateElement("flag");
it.InnerText = "1";
item.AppendChild(it);
}
doc.Save(path);
}
//5.
private void DelNodeChild()
{
//删除节点中的某个属性
string path = Application.dataPath + "/file.txt";
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlNodeList NodesList = doc.SelectSingleNode("Employees").ChildNodes;
XmlNode root = doc.SelectSingleNode("Employees");
foreach (XmlElement item in NodesList)
{
//删除 test 属性
item.RemoveAttribute("test");
//删除节点的子节点
XmlNode no = item.SelectSingleNode("flag");
item.RemoveChild(no);
}
doc.Save(path);
}