C#操作xml文档
1.创建XML文档
XmlDocument doc
= new XmlDocument();
XmlDeclaration dec
= doc
.CreateXmlDeclaration("1.0", "utf-8", null);
doc
.AppendChild(dec
);
XmlElement root
= doc
.CreateElement("root");
doc
.AppendChild(root
);
XmlElement Son1
= doc
.CreateElement("china");
Son1
.SetAttribute("id", "1");
Son1
.SetAttribute("cid", "1");
root
.AppendChild(Son1
);
XmlElement Son2
= doc
.CreateElement("province");
Son2
.InnerText
= "辽宁省";
Son1
.AppendChild(Son2
);
XmlElement Son3
= doc
.CreateElement("city");
Son3
.InnerXml
= "沈阳市";
Son1
.AppendChild(Son3
);
doc
.Save("china.xml");
效果如下
<?xml version
="1.0" encoding
="utf-8"?>
<root
>
<china id
="1" cid
="1">
<province
>辽宁省
</province
>
<city
>沈阳市
</city
>
</china
>
</root
>
添加
XmlDocument doc
= new XmlDocument();
doc
.Load("china.xml");
XmlElement root
= doc
.DocumentElement
;
XmlElement Son1
= doc
.CreateElement("china");
root
.AppendChild(Son1
);
XmlElement Son2
= doc
.CreateElement("province");
Son2
.InnerText
= "北京市";
Son1
.AppendChild(Son2
);
XmlElement Son3
= doc
.CreateElement("city");
Son3
.InnerXml
= "中国村";
Son1
.AppendChild(Son3
);
doc
.Save("china.xml");
效果如下
<?xml version
="1.0" encoding
="utf-8"?>
<root
>
<china id
="1" cid
="1">
<province
>辽宁省
</province
>
<city
>沈阳市
</city
>
</china
>
<china
>
<province
>北京
</province
>
<city
>中关村
</city
>
</china
>
</root
>
删 改 查
找到之后修改,找不到删除
XmlDocument doc
= new XmlDocument();
doc
.Load("china.xml");
XmlNodeList node
= doc
.SelectNodes("root/china");
Console
.WriteLine("--一共存在"+node
.Count
+"个china节点");
int i
=0;
foreach(XmlElement item
in node
)
{
i
++;
if (item
["province"].InnerText
== ("辽宁省"))
{
Console
.WriteLine("第"+i
+"次找到了");
item
["province"].InnerText
= "内蒙古自治区";
item
["city"].InnerText
= "赤峰市";
Console
.WriteLine("修改成功");
}
else
{
Console
.WriteLine("第"+i
+"次没找到");
item
.ParentNode
.RemoveChild(item
);
Console
.WriteLine("删除完成");
}
}
doc
.Save("china.xml");
效果如图
<?xml version
="1.0" encoding
="utf-8"?>
<root
>
<china id
="1" cid
="1">
<province
>内蒙古自治区
</province
>
<city
>赤峰市
</city
>
</root
>
转载请注明原文地址: https://mac.8miu.com/read-510754.html