更新XAttribute值,其中XAttribute Name = X.

我有以下代码,它创建一个包含大量订单信息的XML文件。 我希望能够更新此XML文件中的条目,而不是删除所有内容并重新添加所有内容。

我知道我可以这样做:

xElement.Attribute(attribute).Value = value; 

但是这会改变与属性保持同名的每个属性。 例如,当条目的Id等于“jason”时,我怎么才能改变某事物的价值? 我是否需要加载XML文件,遍历整个文件,直到找到我想要更改的属性匹配,然后更改它,然后再次保存文件?

任何帮助/建议都非常感谢。

 XElement xElement; xElement = new XElement("Orders"); XElement element = new XElement( "Order", new XAttribute("Id", CustomId), new XAttribute("Quantity", Quantity), new XAttribute("PartNo", PartNo), new XAttribute("Description", Description), new XAttribute("Discount", Discount), new XAttribute("Freight", Freight), new XAttribute("UnitValue", UnitValue), new XAttribute("LineTotal", LineTotal) ); xElement.Add(element); xElement.Save(PartNo + ".xml"); 

这是我的XML文件的样子:

      

像这样的东西:

 var doc = XDocument.Load("FileName.xml"); var element = doc.Descendants("Order") .Where(arg => arg.Attribute("Id").Value == "jason") .Single(); element.Attribute("Quantity").Value = "3"; doc.Save("FileName.xml"); 

首先,您需要搜索要更新的元素。 如果找到它,请执行更新。 只需记住在完成后将XDocument保存回文件。

 XDocument doc = ...; var jason = doc .Descendants("Order") .Where(order => order.Attribute("Id").Value == "jason") // find "jason" .SingleOrDefault(); if (jason != null) // if found, { // update something jason.Attribute("Quantity").SetValue(20); } doc.Save(...); // save if necessary 

由于您创建了XML文件,因此您知道XML的根元素,因此您可以使用此代码来获取所需的特定元素:

 TaxonPath = XElement.Parse(xml as string); txtSource.Text = FindGetElementValue(TaxonPath, TaxonPathElement.Source); XElement FindGetElementValue(XElement tree,String elementname) { return tree.Descendants(elementName).FirstOrDefault(); } 

有了这个,您可以获取元素,检查其值,并根据需要进行更改。