0

Sorry for a crappy title. Feel free to change it to a better one.

The problem is this: I have a need to read a set of XML files that look like this:

<rootElement>
   <header>
      <!-- some stuff here -->
   </header>
   <businessContent>
      <oneOfSeveralAllowedSubNodesHereLikeCustomer />
   <businessContent>
</rootElement>

I got xsd.exe to generate C# classes from a schema file I've got and it did it like that (simplified):

public class rootElement
{
   public header header {get;set;}
   public object businessContent {get;set;}
}
// other classes like header and classes for the values
// allowed within business content, say customer

Notice that the type of businessContent is System.Object which is fair enough. The schema says nothing explicitly about what can actually be put in there. But then I have an xml file which has a customer inside its businessContent. customer is defined in the xsd and the xsd.exe generated a class for it as well. I would expect an instance of this class to be created and put as my businessContent but when I read the XML:

var serializer = new XmlSerializer(typeof(rootElement));
var root = (rootElement)serializer.Deserialize(stream));
var customer = (customer)root.businessContent;

I get an exception, because the type of root.businessContent is XmlNode[] and not customer.

So how do I make the serializer to deserialize my object fully, that is with customer and not XmlNode[] inside?

kko
  • 491
  • 1
  • 4
  • 8

1 Answers1

1

Serializing and restoring an unknown class

var extraTypes = new[] { typeof(customer), typeof(otherAllowedSubnodeTypes) };
var serializer = new XmlSerializer(typeof(rootElement), extraTypes);
Community
  • 1
  • 1
Tim S.
  • 55,448
  • 7
  • 96
  • 122
  • This ends up in exception complaining that the anonymous type customer can not be used here – kko May 22 '12 at 03:02
  • Is this a compiler error or a runtime exception? Can you give us the exact error message? `customer` isn't an anonymous type, so I don't understand what you said. – Tim S. May 22 '12 at 11:51
  • it has [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)] – kko May 22 '12 at 23:28
  • The exception is System.InvalidOperationException : Cannot include anonymous type 'customer'. at System.Xml.Serialization.XmlReflectionImporter.IncludeType(Type type, RecursionLimiter limiter) at System.Xml.Serialization.XmlSerializer..ctor(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, String defaultNamespace, String location, Evidence evidence) at System.Xml.Serialization.XmlSerializer..ctor(Type type, Type[] extraTypes) – kko May 22 '12 at 23:32