Search for an element by case insensitive attribute with xdocument

Viewed 439

I have this code for parsing some xml which is working well:

string text = File.ReadAllText("myfile.xml");

XDocument doc = XDocument.Parse(text); //or XDocument.Load(path)

// LINQ to XML query  
XElement alternateSpkgRootElement =
    (from el in doc.Descendants()
    where (string)el.Attribute("name") == "myname" || (string)el.Attribute("Name") == "myname"
    select el).FirstOrDefault();

The problem is my XML can have attributes with capital letters at the start, e.g. instead of el.Attribute("name") it could be el.Attribute("Name").

Is there a nice way to search for these without doing:

where (string)el.Attribute("name") == "myname" || (string)el.Attribute("Name") == "myname"

Edit

Here is some sample XML to show why previously suggested questions do not answer my problem:

<testenv version="1" edition="1" testArchitecture="amd64" xmlns:x="1">
  <x:Copy File="../s34tenv" Ref="22" x:Id="W34CG">
    <x:Set Select="//testlistSearchPath" Name="path" Value="\\s3464\TestMD" />
    <x:Append>
      <chunkRequirement name="BV34n" flavor="amd64fre" />
      <chunkRequirement name="TES34INS" flavor="amd64fre" />
      <param name="InvestigationMappingsFilePath" value="\\red34CG.xml" />
      <param name="Rerun\Enabled" value="True" />
      <param name="_AlternateSpkgRoot" value="\\34MD\AEAuto" />
      <param name="_DeleteETWLogs" value="0" />
      <param name="MinLoadBalanceFactor" value="6" />
      <param name="MaxLoadBalanceFactor" value="12" />
      <param name="Rerun\Attempts" value="1" />
    </x:Append>
  </x:Copy>
  <x:Copy File="../34es.xml" Ref="DES34iles" />
</testenv>
1 Answers

You could add an extension method:

public static class XElementExtensions
{
    public static XAttribute AttributeIgnoreCase(this XElement element, string localName)
    {
        return element.Attributes()
            .FirstOrDefault(x => 
                string.Equals(x.Name.LocalName, localName, StringComparison.OrdinalIgnoreCase));
    }
}

And use like this:

where (string)el.AttributeIgnoreCase("name") == "myname"
Related