5

I have a WCF service where Im building up a block of XML using an XmlWriter. Once complete I want to have the WCF return it as an XmlDocument.

But if I have XmlDocument in the [OperationContract] it doesnt work:

[OperationContract]
XmlDocument GetNextLetter();

The WCF test utility gives:

System.Runtime.Serialization.InvalidDataContractException: Type 'System.Xml.XmlDocument' cannot be serialized.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Blaze
  • 1,863
  • 7
  • 23
  • 40

4 Answers4

14

append xmlserializer on what you did in the operational contract

[OperationContract,XmlSerializerFormat]
XmlDocument GetNextLetter();

this will do it !

Botz3000
  • 39,020
  • 8
  • 103
  • 127
maelo
  • 141
  • 1
  • 2
10

If you are using .Net 3.5 then you can try returning XElement instead - this implements IXmlSerializable, which is the missing ingredient needed to make it work with DataContractSerializer.

Samuel Jack
  • 32,712
  • 16
  • 118
  • 155
3

The DataContractSerializer can serialize XmlElement instances. So just return the DocumentElement property of your XmlDocument instance. See: MSDN.

Szymon Rozga
  • 17,971
  • 7
  • 53
  • 66
2

Don't send the XMLDocument, because you can reconstruct it on the other end.

You should probably send down the string that you want, or construct a business object which can be serialized to XML and transmit that.

Have a look at XSD.exe tool with the .net framework if you have an XSD and you want to make a business object from it which can be serialized.

Spence
  • 28,526
  • 15
  • 68
  • 103
  • 1
    xsd is more XmlSerializer focused - WCF would often use DataContractSerializer... – Marc Gravell Jun 08 '09 at 13:22
  • I guess I've been tainted by legacy XML systems :(. If you're in a greenfield WCF layout then datacontract would probably be a good way to go. – Spence Jun 08 '09 at 13:30