How does Linq-to-Xml convert objects to strings?
Linq-to-Xml contains lots of methods that allow you to add arbitrary objects to an xml tree. These objects are converted to strings by some means, but I can't seem to find the specification of how this occurs. The conversion I'm referring to is mentioned (but not specified) in MSDN.
I happen to need this for javascript interop, but that doesn't much matter to the question.
Linq to Xml isn't just calling .ToString()
. Firstly, it'll accept null
elements, and secondly, it's doing things no .ToString()
implementation does:
For example:
new XElement开发者_开发技巧("elem",true).ToString() == "<elem>true</elem>"
//but...
true.ToString() == "True" //IIRC, this is culture invariant, but in any case...
true.ToString(CultureInfo.InvariantCulture) == "True"
Other basic data types are similarly specially treated.
So, does anybody know what it's doing and where that's described?
Earmon, you are correct.
A quick visit with Reflector* reveals that XElement
and friends will try to cast the value to all the 'simple' types, and then call an appropriate XmlConvert.ToString()
method.
Here's an (slightly edited) excerpt, for illustration:
if (value is string)
{
str = (string) value;
}
else if (value is double)
{
str = XmlConvert.ToString((double) value);
}
// ...
If the object is not a 'simple' type, then obj.ToString() will be used.
This is very nice, because that's almost the only right way to do it.
Of course, you normally want to take with a grain of salt anything based on "that's how it is today". Indeed, MS might one day change how they do it. We don't care -- what matters is that the semantics are carved in stone.
*(Product links are always provided for convenience. I have no relationship with the product or its manufacturer, other than being an indirect customer.)
Update: In Introducing Microsoft LINQ, Pialorsi and Russo confirm this for the other side of the equation (extracting values and casting them), on page 172:
[when casting an XElement to a given type like Decimal] ...the various Explicit [cast] operator overloads internally use XmlConvert from System.Xml or Parse methods of .NET types.
Although I can't find MSDN documentation to support this, when you do something like new XElement("bla",false)
the System.Xml.XmlConvert
class is uses to (de-)serialize the data in a non-localized fashion.
In other words, if anyone else needs to know what exactly linq to xml does when you add a (non-xml) object into an xml tree, look at System.Xml.XmlConvert
.
精彩评论