0

With a LINQ-to-XML query, I have a collection of elements (type IEnumerable<XElement>) and on this collection, I want to update all values of a specific attribute. All updated values can be the same.

Take elements containing these elements:

<element attribute1="value11" attribute2="value21" attribute3="value31" />
<element attribute1="value21" attribute2="value22" attribute3="value33" />
<element attribute1="value31" attribute2="value23" attribute3="value33" />

On elements, how to update all values of attribute1 at the same time?

4

1 回答 1

1

Linq 用于查询。要设置所有值,您可能应该迭代:

我还没有对此进行测试,但我认为这样的事情应该可以解决问题:

var elements = document.Descendants("element");

foreach (XElement e in elements)
{
 if (element.Attribute("attribute1") != null)
        element.Attribute("attribute1").Value = "whateverValue";
    else
        element.Add(new XAttribute("attribute1", "whateverValue"));
}

相关: 使用 LINQ to XML 更新元素?

于 2013-05-24T13:24:04.990 回答