title: select all xml nodes which contain a certain attribute
body: <p>I have to select all nodes which contain an attribute with a certain name.</p>
  
  <p>This is my current, not working approach.</p>
  
  <pre><code>public List&lt;string&gt; RetrieveValuesForAttribute(string attributeName)
  {
      var list = new List&lt;string&gt;();
  
      string xpath = "//*[@Name='" + attributeName + "']";
      XmlNodeList xmlNodeList = document.SelectNodes(xpath);
  
      foreach (XmlNode xmlNode in xmlNodeList)
      {
          list.Add(xmlNode.Attributes[attributeName].InnerText);
      }
  
      return list;
  } 
  </code></pre>
  
  <p>I try to select all nodes which contain the attribute with the name given in the method parameter <code>attributeName</code> and add the value the variable <code>list</code>.</p>
  
  <p><em>Example:</em></p>
  
  <p>This method call:</p>
  
  <pre><code>List&lt;string&gt; result = RetrieveValuesForAttribute("itemSelectedHandler");
  </code></pre>
  
  <p>Should return an list which contains the string "OnSelectedRelatedContactChanged"</p>
  
  <p>This is the xml file:</p>
  
  <pre><code>&lt;GroupBoxWrapper id="gbRelatedContacts" text="Related Contacts"&gt;
    &lt;TabIndex&gt;0&lt;/TabIndex&gt;
    &lt;TabStop&gt;false&lt;/TabStop&gt;
    &lt;PanelWrapper id="pnlRelatedContactsView" width="1350"&gt;
      &lt;TabIndex&gt;0&lt;/TabIndex&gt;
      &lt;TabStop&gt;false&lt;/TabStop&gt;
      &lt;ListViewWrapper id="lvRelatedContacts" itemSelectedHandler="OnSelectedRelatedContactChanged" itemDoubleClickHandler="OnRelatedContactDoubleClick"&gt;
        &lt;TabIndex&gt;0&lt;/TabIndex&gt;
        &lt;TabStop&gt;true&lt;/TabStop&gt;
        &lt;ListViewColumns&gt;
          &lt;Column title="Name" mapNode="Contact\Name" /&gt;
          &lt;Column title="Lastname" mapNode="Contact\Lastname" /&gt;
        &lt;/ListViewColumns&gt;
      &lt;/ListViewWrapper&gt;
    &lt;/PanelWrapper&gt;
  &lt;/GroupBoxWrapper&gt;
  </code></pre>
  
  <p>Further questions:
  Would it be better to solve this with LINQ?</p>
  
  <p><strong>Solution 1:</strong> thank you, ywm</p>
  
  <pre><code>public List&lt;string&gt; RetrieveValuesForAttribute(string attributeName)
  {
      var list = new List&lt;string&gt;();
  
      string xpath = @"//*[@" + attributeName + "]";
      XmlNodeList xmlNodeList = document.SelectNodes(xpath);
  
      foreach (XmlNode xmlNode in xmlNodeList)
      {
          list.Add(xmlNode.Attributes[attributeName].InnerText);
      }
  
      return list;
  }
  </code></pre>
  
  <p><strong>Solution 2:</strong> thank you, Jon Skeet</p>
  
  <pre><code>public List&lt;string&gt; RetrieveValuesForAttribute(string attributeName)
  {
      //document is an XDocument
      return document.Descendants()
                     .Attributes(attributeName)
                     .Select(x =&gt; x.Value)
                     .ToList();
  }
  </code></pre>
  
  <p>The LINQ to XML Solution looks far more elegant to me.</p>