2

Let's say I have the following class layout which defines a one to many relationship between Company and Product:

public class Company
{
    public string Name { get; set; }
    public string Address { get; set; }
}

public class Product
{
    public Company Manufacturer { get; set; }
    public string Name { get; set; }
}

I would like to serialise this into XML, but unfortunately, the Company instance in Product will be duplicated. When I reserialise the document, the duplicated information will be reserialised into two distinct instances.

Because Company and Product are referenced later in the document, it is not possible to invert this relationship. What I need is some method of generating a document that looks like this:

<rootElement>
    <companies>
        <company>
            <id>1</id>
            <name>Apple</name>
            <address>1 Infinite Loop... etc</address>
        </company>
        <company>
            <id>2</id>
            <name>Microsoft</name>
            <address>1 Microsoft Way... etc</address>
        </company>
    </companies>
    <products>
        <product>
            <companyId>1</companyId>
            <name>iPhone</name>
        </product>
        <product>
            <companyId>1</companyId>
            <name>iMac</name>
        </product>
        <product>
            <companyId>2</companyId>
            <name>XBox 360</name>
        </product>
    </products>
</rootElement>

I'm confident that I can hack up some sort of specialised collection to rebuild these references myself, but I'd really like to know what the "correct" method of solving this issue is. There is no way that Microsoft have not thought of this, so there has to be something that I can use in .NET to solve this problem, but I just don't seem to be able to come up with the correct terms to search for.

Steve Rukuts
  • 9,167
  • 3
  • 50
  • 72

1 Answers1

0

If you are doing straight XML serialization and are only concerned about outbound serialization, then you can add an XMLIgnore attribute to the Manufacturer property in Product and add a companyId property for serialization:

[XMLIgnore()]
public Company Manufacturer { get; set; }

public int companyId {
  get {
    return this.Manufacturer.id;
  }
  set {
    // Ignore any updates, only present to support XML serialization
  }
}
competent_tech
  • 44,465
  • 11
  • 90
  • 113