views:

35

answers:

1

Hi, I have a XML doc with parent/child references that I want to deserialize into .NET objects but am unable to do so. Below is the XML snippet:

<family>
  <parents>
    <parent id="1" name="Sam" />
    <parent id="2" name="Beth" />
    <parent id="3" name="Harry" />
  </parents>
  <children>
    <child id="100" name="Tom">
      <parent id="1">
    </child>
    <child id="200" name="Chris">
      <parent id="2">
    </child>
  </children>
</family>

I want to be able to deserialize all the parent tags into the Parents collection using a .NET class as such.

class Child
{
  string Name;
  List<Parent> Parents;
}

class Parent
{
  string Name;
  int Id;
}

Any ideas? I tried Deserialize method on the XmlSerializer class but it only picks up the id attribute but does not relate it back to the parents node collection. Any help is appreciated. Thanks!

A: 

There is a similar question posed here:

http://stackoverflow.com/questions/226599/deserializing-xml-to-objects-in-c

Basically since you stated the XML is hierarchical, you need to put the children indre the appropriate parent. Try using something like this:

<family>
  <parents>
    <parent id="1" name="Sam" >
      <children>
        <child id="100" name="Tom">
          <parent id="1">
        </child>
      </children>
    </parent>
    <parent id="2" name="Beth" />
      <children>
        <child id="200" name="Chris">
          <parent id="2">
        </child>
      </children>
    <parent id="3" name="Harry" />
  </parents>
</family>

That way the children are "beneath" the parent nodes.

kniemczak
thank you for the quick reply but unfortunately i am not allowed to change the xml schema. i have to work with the format given.
Hmmm well with that limitation I am not sure the default deserialization will work. How about as a workaround you use xslt to transform the XML to the schema I posted and then deserializing the transformed XML?
kniemczak