Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to control the de-serialisation of a complex object

I call a third party web service that returns a HUGE amount of XML Data (around 2mb) and I want to deserialise it into an object in a more controlled way than normal. This is the xml:

<vehicle>
  <vehicleManufacturer>
    <type>1</type>
    <name>A Make</name>
  </vehicleManufacturer>
...

I know I can do the below code to control which elements are serialised to which properties, in this case the Car Make object contains two properties, type and name.

    <System.Xml.Serialization.XmlElement("vehicleManufacturer")> _
    Public Property Make() As CarMake

But what I want to be able to do, if possible, is to deserialise just the name field into the Make property, or even just serialise that whole element and it's contents to text.

    <System.Xml.Serialization.XmlElement("vehicleManufacturer")> _
    Public Property Make() As String

This is a hugely simplified example, so if there are any resources that would help me with this, that would be great.

Another example:

<vehicle>
  <warrantyDetail>
    <warrantyBasicInformation buildStartdate="09/07/2013" warrantyStartDate="31/07/2013"/>
  </warrantyDetail>
</vehicle>

I'd like to get the attributes out of warrantyBasicInformation without having to build the warranty detail and warrantyBasicInformation objects.

Note that this sort of thing would usually be generated from the WSDL, however, I won't be provided with one, I don't have an XSD, and trying to generate one failed. I also know I can implement ISerializable and use an xml reader or linq, but again, that can turn into a lot of code and maybe hard to maintain.

like image 650
Mr Shoubs Avatar asked Dec 12 '13 16:12

Mr Shoubs


2 Answers

I had a similar situation some weeks ago where Microsoft's xsd.exe, which you tried to use, failed to generate a reasonable XML schema. I solved the problem using trang, which did the job perfectly. I then used xsd.exe to automatically generate wrapper classes.

This might not fully answer your question, but your life should be easier with an xsd schema.

like image 199
Antitoon Avatar answered Sep 23 '22 05:09

Antitoon


We have been using Xsd2Code for a while for reading xml files. All these files have an XSD behind it that helps generation (I think XSD is the only way you get this sorted out without a lot of hand-crafted code, if giving problems, try to write it yourself, it isn't that hard).

Xsd2Code generates a code file with Serialize and Deserialize methods like this:

repositoryAsXml = settings.Serialize();

and

icn_database_v database;

if (!icn_database_v.Deserialize(xmlContents, out database, out exception))
{
    throw exception;
}
like image 43
Patrick Hofman Avatar answered Sep 24 '22 05:09

Patrick Hofman