C#怎样删除XML指定节点和全部属性
1个回答
展开全部
假设XML文件为:
<?xml version="1.0" encoding="utf-8"?>
<Connections>
<Server1>
<IP>173.1.0.1</IP>
<DataBase>Book</DataBase>
<User>sa</User>
<PassWord>sa</PassWord>
</Server1>
<Server2>
<IP>123.5.1.3</IP>
<DataBase>Test</DataBase>
<User>sa</User>
<PassWord>da</PassWord>
</Server2>
</Connections>
/// <summary>
/// 删除指定节点信息
/// </summary>
/// <param name="nodeTag"></param>
public void DeleteXml(string nodeTag)
{
XmlNode root = xmlDoc.SelectSingleNode("Connections");
if (root.HasChildNodes)//如果有子节点
{
XmlNodeList nodelist = root.ChildNodes;
for (int i = 0; i < nodelist.Count; i++)
{
if (nodelist[i].Name == nodeTag)
{
nodelist[i].ParentNode.RemoveChild(nodelist[i]);
}
else
{ }
}
}
else
{ }
}
//现在要删除Server1节点内的所有信息,nodeTag=="Server1"
private void button1_Click(object sender, EventArgs e)
{
string XmlFilePath = Application.StartupPath + "\\test.xml";
if (File.Exists(XmlFilePath))
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(XmlFilePath);
DeleteXml("Server1");
xmlDoc.SaveXml(XmlFilePath);
}
else
{
MessageBox.Show("路径下Xml文件不存在!");
}
}
删除后XML文件:
<?xml version="1.0" encoding="utf-8"?>
<Connections>
<Server2>
<IP>123.5.1.3</IP>
<DataBase>Test</DataBase>
<User>sa</User>
<PassWord>da</PassWord>
</Server2>
</Connections>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询