0

I've got an XML document like this:

<?xml version="1.0" encoding="utf-8"?>
<Settings updated="3/21/2017 15:48">
  <Setting name="ToolTipVariables">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  &lt;string&gt;Title&lt;/string&gt;
  &lt;string&gt;Date&lt;/string&gt;
  &lt;string&gt;Description&lt;/string&gt;
  &lt;string&gt;Location&lt;/string&gt;
  &lt;string&gt;Id&lt;/string&gt;
&lt;/ArrayOfString&gt;</Setting>
  <Setting name="ToolTipVariables">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  &lt;string&gt;Title&lt;/string&gt;
  &lt;string&gt;Date&lt;/string&gt;
  &lt;string&gt;Description&lt;/string&gt;
  &lt;string&gt;Location&lt;/string&gt;
  &lt;string&gt;Id&lt;/string&gt;
&lt;/ArrayOfString&gt;</Setting>
  <Setting name="ToolTipVariables">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  &lt;string&gt;Title&lt;/string&gt;
  &lt;string&gt;Date&lt;/string&gt;
  &lt;string&gt;Description&lt;/string&gt;
  &lt;string&gt;Location&lt;/string&gt;
  &lt;string&gt;Id&lt;/string&gt;
&lt;/ArrayOfString&gt;</Setting>
  <Setting name="ShowUpdateWindow">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;boolean&gt;true&lt;/boolean&gt;</Setting>
</Settings>

And I'm trying to grab the first "ToolTipVariables" element like this:

XDocument document = XDocument.Load(settingsPath); //settingsPath is where the XML Document is located
XElement element = document.Descendants("Settings").Where(x => x.Attribute("name").Value == "ToolTipVariables").FirstOrDefault();

but it keeps throwing a null reference exception when trying to get the FirstOrDefault. Maybe I'm making a simple mistake somewhere, but I can't find it. Any help would be appreciated!

derekantrican
  • 1,891
  • 3
  • 27
  • 57
  • Clearly `x.Attribute("name")` must be null in some cases, so you want `Where(x => (string)x.Attribute("name") == "ToolTipVariables")` – dbc Mar 25 '17 at 16:36

1 Answers1

2

The problem is that you are selecting all elements called Settings (where that is actually the root node.) The code document.Descendants("Settings") will give you all descendants of the document where the element name is Settings. I think what you really want is all Setting elements. This will work:

XElement element = document.Descendants("Setting")
    .Where(x => x.Attribute("name").Value == "ToolTipVariables")
    .FirstOrDefault();
DavidG
  • 113,891
  • 12
  • 217
  • 223
  • 1
    Ah - there's the stupid mistake ;) . I misunderstood "Descendants" to mean "Descendants OF this" not "Descendants NAMED this". Thank you! – derekantrican Mar 25 '17 at 16:41