簡體   English   中英

Linq Xml - 按值查找屬性

[英]Linq Xml - Find attributes by value

如果我有一個簡單的XML文檔,如

<case id="37d3c93c-3201-4002-b24f-08e1221c3cb7">
    <party id="26dad8c5-9487-48f2-8911-1d78c00095b2">...</party>
    <illustration CaseId="37d3c93c-3201-4002-b24f-08e1221c3cb7">....</illustration>
    <illustration CaseId="37d3c93c-3201-4002-b24f-08e1221c3cb7">....</illustration>
    <item relatedCaseId="37d3c93c-3201-4002-b24f-08e1221c3cb7">...</illustration>
</case>

我有更改case元素的id屬性的代碼。 我現在正在尋找一些LINQ代碼,它可以幫助我搜索具有與舊值匹配的屬性值的所有元素,因此我可以用新值替換它。 我沒有屬性名稱列表,需要搜索整個文檔。

任何提示/想法? 謝謝!

像這樣的東西:

var matches = doc.Descendants()
                 .Where(x => x.Attributes()
                              .Any(attr => attr.Value == oldValue));

或者,如果您只是嘗試替換值,則只需要屬性本身:

var attributes = doc.Descendants()
                    .Attributes()
                    .Where(attr => attr.Value == oldValue)
                    .ToList();
foreach (var attribute in attributes)
{
    attribute.Value = newValue;
}

在這種情況下,完全有可能將副本復制到列表中,但我通常更喜歡在改變XDocument時制作副本以避免混淆。 (當你刪除一個元素或類似的東西時,這當然是必要的 - 只是設置一個屬性的值可能不會影響事物。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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