C#替换已存在的xml属性

时间:2012-03-26 09:45:46

标签: c# c#-4.0

我正在开发一个C#winform项目,我在我的应用程序中解析了一些xml。当我检查一些条件时,我试图更改属性值,但我得到一些错误。这是我的代码:

If(mycondition){
 writer.WriteAttributeString("type","loopTask");
}

我必须提到我的xml文件中已经存在属性“type”,我得到错误'type'是一个重复的属性名称。我怎样才能取代价值?实现这项任务的最简单方法是什么?

1 个答案:

答案 0 :(得分:1)

更改属性的一种方法可能是:

//Here is the variable with which you assign a new value to the attribute
string newValue = string.Empty 
XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(xmlFile);

XmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element");
node.Attributes[0].Value = newValue;

xmlDoc.Save(xmlFile);

//xmlFile is the path of your file to be modified