0

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?

  • Yes, it is. As long as you generate proper content into `XmlWriter` instance your implementation is correct. – MarcinJuraszek Aug 27 '13 at 14:29
  • I don't think that this is called "linq-to-xml". This is simply another way to create a xml file. – Ondrej Janacek Aug 27 '13 at 14:54
  • @Andrew Ahh yes. My example is a bit too simplified. My implementation does actually include linq queries over some enumerable members. – Nathan Phetteplace Aug 27 '13 at 18:34
  • 1
    Then you should change the name of your question, because this is confusing. Answer to your question is rather simple. Yes, it is acceptable. But I don't actually think, this is an appropriate question. Maybe describe, why do you implement IXmlSerializabe instead of just using XmlAttribute/XmlElement/... and serializing using existing XmlSerializer? – Ondrej Janacek Aug 28 '13 at 07:48

1 Answers1

2

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.

Jumast
  • 101
  • 3