deserialize object

  • Thread starter Thread starter Peter K
  • Start date Start date
P

Peter K

Hi

I call a url, and recive a string back - which is xml-like. That is, it
looks something like the following (a list of <case>s, containing various
items of data.):

<case>
<id>123</id>
<name>Peter K</name>
<group>6</group>
</case>
<case>
<id>321</id>
<name>Arnold B</name>
<group>6</group>
</case>


How can I best "deserialize" this xml to a list of objects?

At the moment I add a <cases> tag around the return string, and call
XmlDocument.LoadXml, and manually loop through the nodes "case", "id",
"name" etc, building up a list of Case objects.

But I wonder if I could use something more "automatic", like
XmlSerializer.Deserialize? Can this handle a list of objects - and what if
the xml-node names do not match the property names in my Case class, can I
provide a mapping for this?


Thanks,
Peter
 
Hi

I call a url, and recive a string back - which is xml-like. That is, it
looks something like the following (a list of <case>s, containing various
items of data.):

<case>
  <id>123</id>
  <name>Peter K</name>
  <group>6</group>
</case>
<case>
  <id>321</id>
  <name>Arnold B</name>
  <group>6</group>
</case>

How can I best "deserialize" this xml to a list of objects?

At the moment I add a <cases> tag around the return string, and call
XmlDocument.LoadXml, and manually loop through the nodes "case", "id",
"name" etc, building up a list of Case objects.

But I wonder if I could use something more "automatic", like
XmlSerializer.Deserialize? Can this handle a list of objects - and what if
the xml-node names do not match the property names in my Case class, can I
provide a mapping for this?

Thanks,
Peter

Hello!

The XmlSerializer is made for this job.
When Xml node names and object properties don't match, you have the
ability to "tag" your properties with attributes.
The System.Xml.Serialization namespace has XmlAttributes and
XmlElements attributes (and more) for this purpose.
 
Hello!

The XmlSerializer is made for this job.
When Xml node names and object properties don't match, you have the
ability to "tag" your properties with attributes.
The System.Xml.Serialization namespace has XmlAttributes and
XmlElements attributes (and more) for this purpose.

Right, thanks. Is it possible to declare a "custom converter"? I mean, I
have xml that looks like this:

<completed>20090831</completed>

which represents the date "31 August 2009". Is there an XmlElement tag or
something I can put in my class which tells it how to convert this string to
a DateTime?

I have a property like:

[XmlElement("completed")]
public DateTime? CompletionDate
{
get;
set;
}

How can I tell the deserializer how to convert "20090831" to the relevant
DateTime?



Thanks,
Peter
 
Back
Top