I am new to LINQ and using it to query XML (it’s incredible). I have the following function which simply creates a new List object for each list descendant found in the XML.:
public void ParseLists(XDocument xDoc)
{
XNamespace ns = xDoc.Root.Name.Namespace;
AddRange((
from e in xDoc.Descendants(ns + "list")
select new List
{
Id = (string)e.Element(ns + "id"),
ItemsLink = (string)e.Element(ns + "items-link"),
BatchLink = (string)e.Element(ns + "batch-link"),
Name = (string)e.Element(ns + "name"),
IsVendor = (string)e.Element(ns + "is-vendor"),
Levels = (string)e.Element(ns + "levels")
}).ToList());
}
And here’s a snippet of what the XML might look like:
<lists xmlns="www.namespaceurl.com" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<list>
<batch-link>www.batchlinkurl.com</batch-link>
<id>12345</id>
. . .
</list>
</lists>
The Question: When building the List objects, I initially used Convert.ToString() rather than (string) to get the elements values as a string. What I found was that:
Convert.ToString(e.Element(ns + "id")) will return <id>12345</id>
whereas
(string)e.Element(ns + "id") will return 12345.
Can someone explain why the return value is different?
Convert.ToString(...)will call the overriddenToString()method, which returns the element itself as a string.(string) ...will use the overloaded explicit conversion to string operator, which returns the text contents of the element as a string.