C# – an appropriate XML type for web service


Current Implementation

Sql Server 2005 Database with a table called messages with a column called MessageXml of type xml.

C# Library project with a Linq to Sql class that generates a class called Message with a field called MessageXml of type XElement.

WCF Webservice that exposes a MessagePayload class with a property called MessageXml of type XElement.

The webservice doesn't serve up my Message class created by Linq to Sql. I use a light weight object as a go between.


Is XElement really the type I want to be using in my WCF Service or is there a better type. The xml that is intended to be passed into the service should be a full doc. Also, I'm having a bit of trouble loading xml documents as an XElement. I think that I should expose a full xml document type in the light weight class for the service but I'm a bit confused on the differences between XDocument and XmlDocument.

On top of that, I can't expose the WCF Message class with a property of XDocument type because it contains a property of XDeclaration type that can't be serialized.

If I use XmlDocument than I have to do this weird conversion of xml types in my translation between the Linq class and the lightweight class.

 XmlDocument doc = new XmlDocument();

 MessageEnvelope retVal = new MessageEnvelope()
      MessageXml = doc,

XmlDocument seems like the right one and I know I'll have to do some translation but want to get as close to appropriate as possible.

Best Solution

You can use either XElement or XmlElement:

public XmlElement GetXmlElement()
    var doc = new XmlDocument();
    doc.Load(PREFIX + @"Enumerations.wsdl");

    return doc.DocumentElement;

public XElement GetXElement()
    var doc = XDocument.Load(PREFIX + @"Enumerations.wsdl");
    return doc.Root;

You do not want either XDocument nor XmlDocument. Remember that whatever you return will be in the middle of an XML document containing the SOAP envelope. You can't have a document inside a document, so what you want is an element.