Search code examples
c#linq-to-xmlixmlserializable

Using LINQ to XML to implement IXmlSerializable


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?


Solution

  • 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:

    public void WriteXml(XmlWriter writer)
    {
        new XElement("Name", _name).WriteTo(writer);
        new XElement("X", _x).WriteTo(writer);
        new XElement("Y", _y).WriteTo(writer);
    }
    

    Besides, when you call

    writer.WriteElementString("X", _x.ToString());
    

    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.