If I have a simple XML document such as
<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>
I have code that changes the id attribute of the case element. I am now looking for some LINQ code that would help me search all elements that have an attribute value that matches the old value so I can replace it with the new value. I do not have a list of attribute names, and would need to search the entire document.
Any tips/ideas? Thanks!
Something like this:
var matches = doc.Descendants()
.Where(x => x.Attributes()
.Any(attr => attr.Value == oldValue));
Or if you're just trying to replace the values, you only need the attributes themselves:
var attributes = doc.Descendants()
.Attributes()
.Where(attr => attr.Value == oldValue)
.ToList();
foreach (var attribute in attributes)
{
attribute.Value = newValue;
}
It's entirely possible that the copy to a list isn't necessary in this case, but I generally prefer to make a copy when mutating an XDocument
to avoid confusing things. (It's certainly necessary when you're removing an element or something like that - just setting the value of an attribute probably doesn't affect things.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.