I feel like this is probably a duplicate, but I can't find the exact answer I'm looking for. I am implementing IXmlSerializable on an object and want to know if it would be acceptable to use linq-to-xml.
Replace this...
public void WriteXml(XmlWriter writer)
{
writer.WriteElementString("Name", _name);
writer.WriteElementString("X", _x.ToString());
writer.WriteElementString("Y", _y.ToString());
}
with this...
public void WriteXml(XmlWriter writer)
{
XElement element =
new XElement("MyObj",
new XElement("Name", _name),
new Xelement("X", _x),
new Xelement("Y", _y)
);
element.WriteTo(writer);
}
My actual implementation is obviously more complex to the point that I feel the linq-to-xml structure is simpler and more readable. Is the above acceptable?
The first implementation doesn't generate the same xml as the second one. You should write the second implementation as follows to match the xml generated by the first one:
Besides, when you call
the result could be non XML-compliant and vulnerable to incorrect parsing, depending on _x type (for example, if type of _x is DateTime), so the second implementation is better, at least in this regard.
I got some of this info from C# 5 in a Nutshell.