使用xdocument通过不区分大小写的属性搜索元素

问题描述 投票:2回答:1

我有这段代码可以很好地解析某些xml:

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();

问题是我的XML开头可能带有大写字母的属性,例如而不是el.Attribute("name")可能是el.Attribute("Name")

是否有一种不错的方式搜索这些内容而无需这样做:

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

编辑

这里有一些示例XML,以说明为什么先前建议的问题不能解决我的问题:

<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>
c# xml linq-to-xml
1个回答
2
投票

您可以添加扩展方法:

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));
    }
}

并且像这样使用:

where (string)el.AttributeIgnoreCase("name") == "myname"
© www.soinside.com 2019 - 2024. All rights reserved.