簡體   English   中英

C#Linq To Xml-如何選擇元素集合並使用lambda進行修改?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM