[英]C# Linq To Xml - How do Select collection of elements and modify each using lambda?
我想從XDocument中選擇元素,並在單個lambda表達式中為每個元素添加一個屬性。 這是我正在嘗試的:
xhtml.Root.Descendants()
.Where(e => e.Attribute("documentref") != null)
.Select(e => e.Add(new XAttribute("documenttype", e.Attribute("documentref").Value)));
正確的方法是什么?
謝謝!
由於LINQ的執行延遲,因此如果從不迭代語句的結果,則不會將屬性添加到XML。
var elementsWithAttribute = from e in xhtml.Root.Descendants()
let attribute = e.Attribute("documentref")
where attribute != null
select e;
foreach (var element in elementsWithAttribute)
element.Add(...);
xhtml.Root.Descendants()
.Where(e => e.Attribute("documentref") != null)
.ToList()
.ForEach(e => e.Add( new.... ) );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.