Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize/deserialize generated WCF proxy code?

I am trying to serialize/deserialize generated WCF web service proxy code from svcutil. While I'm able to serialize the objects, I'm not able to deserialize them back to objects. Here's the XML I generated through serialization:

<RootObject xmlns="http://schemas.myco.com/online/sync/2008/11">
    <WrapperObject>
        <Objects>
            <SomeObject p4:type="Foo" ContextId="d5f9f021-b2a1-47ba-9f25-1e068194dc87" ObjectId="fad3ef87-3944-459d-b45b-1e4e52ef24db" xmlns:p4="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.myco.com/online/sync/2008/11" />
        </Objects>
      </WrapperObject>
</RootObject>

I have a couple questions:

  1. I am already using XmlSerializerNamespaces to declare the namespace to match the namespace specified in the generated proxy code. How come there is still a "p4" tag that it added to the "SomeObject" tag and a new xml namespace added (xmlns:p4="http://www.w3.org/2001/XMLSchema-instance").

        using (XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, xmlSettings))
        {
            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
            namespaces.Add(string.Empty, defaultNamespace);
    
            XmlSerializer serializer = new XmlSerializer(typeof(T), defaultNamespace);
            serializer.Serialize(xmlWriter, objectToBeSerialized, namespaces);
    
            return stringBuilder.ToString();
        }
    
  2. When I try to deserialize the XML with the following code, I get the following error: "System.InvalidOperationException: There was an error generating the XML document. ---> System.Xml.XmlException: 'p4:type' is a duplicate attribute name."

        using (TextReader textReader = new StringReader(xmlString))
        {
            using (XmlReader xmlReader = XmlReader.Create(textReader))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T), defaultNamespace);
                return (T)serializer.Deserialize(xmlReader);
            }
        }
    
  3. The proxy code is generated by svcutil to communicate with a WCF web service. All generated objects are serialized/deserialized properly when I just use the web service call.

Has anyone had similar problems before?

like image 967
Bryan Avatar asked Oct 15 '22 00:10

Bryan


1 Answers

WCF uses specialized XML serializers to serialize objects which will generate XML differently from the standard XmlSerializer. You can use XmlSerializer, but you're going to have to properly attribute your class for the object objectToBeSerialized. It's probably better just to use the WCF serializers instead.

Take a look at this article:

http://msdn.microsoft.com/en-us/magazine/cc163569.aspx

like image 112
ATL_DEV Avatar answered Nov 01 '22 15:11

ATL_DEV