0

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!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
HBCondo
  • 895
  • 3
  • 10
  • 26

1 Answers1

0

There is a similar question posed here:

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.

Community
  • 1
  • 1
kniemczak
  • 359
  • 1
  • 4
  • 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. – HBCondo Jul 27 '10 at 20:51
  • 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 Jul 27 '10 at 21:05