Simon Griffiths
Simon Griffiths

Reputation: 165

C# XML Deserialization into multiple objects

I am deserializing a given XML file into a single object, which I have working fine. However, I now which to adapt the XML file so that I extra attributes, which should be deserialized into a separate object, so from the one given xml file i can populate two objects, is this possible within one operation?

Here is my current code and XML:

XML As it is now:

<NameCollection>
   <Names>
      <Name>
        <description></description>
      <Name>
      <Name>
        <description></description>
      <Name>
   </Names>
</NameCollection>

XML As I wish it to be:

<NameCollection>
  <GenericName></GenericName>
  <GenericDescription></GenericDescription>
   <Names>
      <Name>
        <description></description>
      <Name>
      <Name>
        <description></description>
      <Name>
   </Names>
</NameCollection>

Code:

NameCollection commands;

XMLSerializer serializer = new XMLSerializer(typeof(NameCollection));
StreamReader streamReader = new StreamReader(xmlpath);

commands = (NameCollection)serializer.Derserialize(streamreader);

streamReader.Close();

And the current object:

[Serializable()]
public class TestCommand
{
   public string description{get;set;}
}

[Serializable()]
[XmlRoot("NameCollection")]
public class NameCollection
{
   [XmlArray("Commands")]
   [XmlArrayItem("Command", typeof(TestCommand))]
   public TestCommand[] TestCommand {get;set;}
}

I then wish to add GenericName and GenericDescription attributes to another separate object, this is what im stuck on.

Upvotes: 1

Views: 5001

Answers (2)

Liam
Liam

Reputation: 29760

I think what your after is to have your class reflect the structure of the XML, rather than two classes. So you want a structure like:

public class TestCommand
{
   public string description{get;set;}
}

[XmlRoot("NameCollection")]
public class NameCollection
{
    public string GenericName {get; set;}
    public string GenericDescription {get; set;}

   [XmlArray("Commands")]
   [XmlArrayItem("Command", typeof(TestCommand))]
   public TestCommand[] TestCommand {get;set;}
}

then serialize it in exactly the same way, job done.

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1064324

With the layout you have, the only place XmlSerializer is going to want to put those extra values is on NameCollection, i.e.

[XmlRoot("NameCollection")]
public class NameCollection
{
    public string GenericName {get;set:}
    public string GenericDescription {get;set:}

    [XmlArray("Names")]
    [XmlArrayItem("Name", typeof(TestCommand))]
    public TestCommand[] TestCommand {get;set;}
}

If you want it to go on some other object, then: XmlSerializer isn't going to do that.

Upvotes: 2

Related Questions