Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ/XML:如果属性名称包含某个关键字,则获取属性值_C#_Xml_Linq_Xdoc - Fatal编程技术网

C# LINQ/XML:如果属性名称包含某个关键字,则获取属性值

C# LINQ/XML:如果属性名称包含某个关键字,则获取属性值,c#,xml,linq,xdoc,C#,Xml,Linq,Xdoc,由于我对LINQ和xDocument不是很熟悉,我很难实现以下内容: 我有一个XML文件,看起来像 <document> <attribut1/> <attribut2> <house price="100" location="UK" id-ext="Id-100"/> <house price="300" location=

由于我对LINQ和xDocument不是很熟悉,我很难实现以下内容: 我有一个XML文件,看起来像

<document>
   <attribut1/>
   <attribut2>
      <house price="100" location="UK" id-ext="Id-100"/>
      <house price="300" location="GB" id-int="Id-101"/>
   </attribut2>
   <attribut3/>
</document>
用伪代码来说,我需要

输入:xDocument

输出:包含所有值的字符串的列表,在本例中为Id-100,其中Id ext包含在属性名称中。因此,我尝试获取那些名称中包含某些字母的属性的值

我已经搜索过类似的建议,如此处所述: 但关键是,这里返回的是整个XML节点,我无法将其分解为属性名称

如果您能给我一些建议,告诉我如何在应用子体以获取属性名称中包含某些关键字的属性值后移动一个属性,我将不胜感激。

请使用字典

            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, List<XElement>> dict = doc.Descendants("house")
                .Where(x => x.Attribute("id-ext") != null)
                .GroupBy(x => (string)x.Attribute("id-ext"))
                .ToDictionary(x => x.Key, y => y.ToList());

假设关键字包含在属性名称中,则表示属性名称作为字符串包含特定的子字符串,并且该属性可能出现在文档中的任何元素上:

var doc = XDocument.Parse(@"<document>
<attribut1/>
<attribut2>
   <house price='100' location='UK' id-ext='Id-100'/>
   <house price='300' location='GB' id-int='Id-101'/>
</attribut2>
<attribut3/>
</document>");

foreach (var s in doc
  .Descendants()
  .SelectMany(e => e.Attributes())
  .Where(a => a.Name.LocalName.Contains("id-ext"))
  .Select(a => a.Value))
{
    Console.WriteLine(s);
}

谢谢你的帮助!:-我非常感谢你的建议,因为我不必在这里指定属性名称。