Search code examples
c#xmllinqxdoc

LINQ/XML: Get the attribut value if the attribut name contains a certain key word


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.


Solution

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