- Experts Exchange Approved
Unfortunately, there is *no way* to get this exact piece of XML is in the current version of WCF as attributes in XML streams are not supported using DataContract!
The solution to follow uses the 'KnownType' WCF attribute to piggyback the Microsoft 'i:type' attribute. Using the method described in this article, we can get close to the above (desired) XML as the output we get looks like this:
Notice the difference is the addition of namespace 'i' that changes 'type' to 'i:type'. If you can live with the 'i:' prefix, this solution is for you.
With that said, let's get under way with a sample definition of a WCF service that will use my technique.
GetUserXML is a function declaration in a .svc file. It is a RESTful (REpresentational State Transfer) Web Service call which would be invoked like this.
The function returns an 'info' class as 'plain' serialized XML to the caller. Within the plain serialized XML will be the embedded attributes. Each attribute that will appear in the serialized XML must be declared as a KnownType and have its own class implementation. The code below shows a base class that defines two KnownTypes.
The Args FirsNameArg and LastNameArg can now be used in the info class.
The info class results in the outer tag:
info declares an array of BaseArg with a [DataMember] contract of "args" resulting in:
Each BaseArg that is added results in an <arg> tag with an i:type inside it. The code DataContract(Name="firstna
The value passed to the BaseArg classes 'Value' function becomes the body of the arg:
And so on for other args...
A simplified version of the function body for GetUserXML could be seen here:
Although not an ideal solution to the attribute problem, this tutorial will help you move forward if you are blocked by the need for dynamic XML attributes in WCF.
WilliamCampbell
References:
XML Attributes: http://www.w3schools.com/X
DataContracts: http://msdn.microsoft.com/
KnownType: http://msdn.microsoft.com/
RESTful Web Services: http://www.developer.com/n
Original EE Question: http://www.experts-exchang