Exception: XPath expression evaluates to unexpected type System.Xml.Linq.XAttribute

I have an XML file as shown below:

<Employees> <Employee Id="ABC001"> <Name>Prasad 1</Name> <Mobile>9986730630</Mobile> <Address Type="Perminant"> <City>City1</City> <Country>India</Country> </Address> <Address Type="Temporary"> <City>City2</City> <Country>India</Country> </Address> </Employee> 

Now I want to get all types of addresses.

I tried as shown below using XPath and I get an exception.

 var xPathString = @"//Employee/Address/@Type"; doc.XPathSelectElements(xPathString); // doc is XDocument.Load("xml file Path") 

Exception: an XPath expression evaluates to an unexpected type of System.Xml.Linq.XAttribute.

Is there a problem with my XPath?

+5
source share
1 answer

Your XPath is fine (although you might want it to be more selective), but you have to tweak how you rate it ...

XPathSelectElement() , as its name implies, should only be used to select items.

XPathEvaluate() is more general and can be used for attributes. You can list the results or grab the first one:

 var type = ((IEnumerable<object>)doc.XPathEvaluate("//Employee/Address/@Type")) .OfType<XAttribute>() .Single() .Value; 
+8
source

All Articles