-1

Since I am not very familiar with LINQ and xDocument, I struggle to implement the following: I have a XML file which looks like

<document>
   <attribut1/>
   <attribut2>
      <house price="100" location="UK" id-ext="Id-100"/>
      <house price="300" location="GB" id-int="Id-101"/>
   </attribut2>
   <attribut3/>
</document>

Speaking in Pseudo Code I need something like

Input: xDocument

Output: List containing strings with all values, i.e. "Id-100" in this example, of those attributes where "id-ext" was included in the attribut name. Hence, I try to get the values of those attributes which contain some certain letters in their name.

I already searched for similar suggestions like the one stated here: How to search entire XML file for keyword? But the point is that here the whole XML-Node is returned and I don't manage to break it down to the name of an attribute.

I would appreciate any suggestions of how to move one after applying "Descendants" to get the values of those attributs where some keywords are contained in the attribut name.

Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
Confucius
  • 37
  • 5

2 Answers2

2

Use a dictionary

            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());
jdweng
  • 33,250
  • 2
  • 15
  • 20
0

Assuming "keywords are contained in the attribut name" means that the attribute name as a string contains a specific substring, and that this attribute may occur on any element in the document:

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);
}
Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
  • Thank you for your help! :-) I really appreciate your suggestion since I do not have to specify the attribut name here. – Confucius Aug 19 '20 at 12:10