How to select all attributes that contain a specific string in an XML document using LINQ

Like XPath: How to match attributes that contain a specific string , but without using XPath. Is it possible?

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

      

Basically I want to select all attribute values ​​in the document that their attribute name contains "Foo", so it should return the values ​​"BarFoo", "FooBar", "Foo" (va1, val2, val3)

+2


a source to share


2 answers


Like this:



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

      

+1


a source


My starting point is parsing the XML string into an XElement object.

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

      



The result is an IEnumerable of an anonymous type that contains each attribute name and value.

BarFoo  val1
Foo     val2
FooBar  val3

      

0


a source







All Articles