views:

57

answers:

2

Similar to XPath: How to match attributes that contain a certain 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 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)

A: 

Like this:

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

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 of that is an IEnumerable of an anonymous type containing each attribute's name and value.

BarFoo  val1
Foo     val2
FooBar  val3
Anthony Pegram