-1

由于我对 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 文件中搜索关键字? 但关键是这里返回了整个 XML 节点,我无法将其分解为属性名称。

我将不胜感激在应用“后代”以获取属性名称中包含某些关键字的那些属性的值之后如何移动一个的任何建议。

4

2 回答 2

2

使用字典

            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());
于 2020-08-19T11:21:10.117 回答
0

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

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);
}
于 2020-08-19T11:47:27.090 回答