<Items>
<item id=”1”>one</item>
<item id=”2”>two</item>
<item>three with no id attribute</item>
<item>three with no id attribute</item>
</Items>
If you query the document with the following syntax: (get all the items with the attribute id)
var nodes = (from item in Xml.Descendants()
where item.Attribute(NodeId) != null
select item).ToList<XElement>();
If the NodeId string variable has no value, the exception of the invalid expanded name will be raised. To address this, we should check that the string is not empty before executing the LINQ query. We can also rewrite the query to something like this:
var nodes = (from item in Xml.Descendants()
where (!String.IsNullOrEmpty(NodeId) && item.Attribute(NodeId) != null)
select item).ToList<XElement>();
The IsNUllOrEmpty call prevents the execution of the attribute call when NodeId is empty.
I hope this helps.