[英]Linq Xml - Find attributes by value
If I have a simple XML document such as 如果我有一个简单的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>
I have code that changes the id attribute of the case element. 我有更改case元素的id属性的代码。 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.
我现在正在寻找一些LINQ代码,它可以帮助我搜索具有与旧值匹配的属性值的所有元素,因此我可以用新值替换它。 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. 在这种情况下,完全有可能将副本复制到列表中,但我通常更喜欢在改变
XDocument
时制作副本以避免混淆。 (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.) (当你删除一个元素或类似的东西时,这当然是必要的 - 只是设置一个属性的值可能不会影响事物。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.