简体   繁体   English

如何使用LINQ选择XML文档中包含某些字符串的所有属性

[英]How to select all the attributes that contain certain String in an XML Document using LINQ

Similar to XPath: How to match attributes that contain a certain string but without using XPath. XPath相似:如何匹配包含特定字符串但不使用XPath的属性 Is it possible? 可能吗?

<c BarFoo="val1">
   <d Foo="val2" someAttribute="">
      <e FooBar="val3" />
   </d>
</c>

Basically I want to select all the attribute values in the document that their attribute name contains "Foo", so it should return the values of "BarFoo", "FooBar", "Foo" (va1, val2, val3) 基本上,我想选择文档中所有属性值包含“ Foo”的属性值,因此它应该返回“ BarFoo”,“ FooBar”,“ Foo”的值(va1,val2,val3)

像这样:

elem.DescendantsAndSelf().Attributes().Where(a => a.Name.LocalName.Contains("Foo"))

My starting point is parsing the XML string into an XElement object. 我的出发点是将XML字符串解析为XElement对象。

var query = element.DescendantsAndSelf().Attributes()
    .Where(attr => attr.Name.LocalName.Contains("Foo"))
    .Select(attr => new { Name = attr.Name, Value = attr.Value });

The result of that is an IEnumerable of an anonymous type containing each attribute's name and value. 结果是匿名类型的IEnumerable,其中包含每个属性的名称和值。

BarFoo  val1
Foo     val2
FooBar  val3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM