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

时间:2011-05-19 03:57:01

标签: c# .net xml linq linq-to-xml

我有以下代码,它创建一个带有大量订单信息的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文件:

<?xml version="1.0" encoding="utf-8"?>
<Orders>
    <Order Id="V45Y7B458B" Quantity="2" PartNo="5VNB98" Description="New Custom Item Description" Discount="2.00" Freight="2.90" UnitValue="27.88" LineTotal="25.09" />
    <Order Id="jason" Quantity="2" PartNo="jason" Description="New Custom Item Description" Discount="2.00" Freight="2.90" UnitValue="27.88" LineTotal="25.09" />
</Orders>

3 个答案:

答案 0 :(得分:8)

这样的事情:

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");

答案 1 :(得分:3)

首先,您需要搜索要更新的元素。如果找到它,请执行更新。只需记住在完成后将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

答案 2 :(得分:3)

由于您创建了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();
}

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

相关问题