Turach
Turach

Reputation: 21

Attributes vs. Elements in the DataContractSerializer

I need to realise such structure:

Emplooyee:

Each employee may have more than one customer, all data should be stored/loaded to/from xml file using xml-serialization, business fields should be stored in xml as attributes.

public class AllEntities
{
    public AllEntities()
    {
        Create();        
    }

    public List<Employee> allEmployees { get; set; }

    public List<Customer> allCustomers { get; set; }

    public List<Business> allBusiness { get; set; }

    private void Create()
    {
        allCustomers = new List<Customer> { new Customer ("Company1", "Minsk", "1236547", "[email protected]", false), 
                                            new Customer("Company2", "Minsk", "7896589", "[email protected]", false)};
        allBusiness = new List<Business> { new Business("Programming", "Short description"),
                                           new Business("Desin", "Short description")};

        allEmployees = new List<Employee> { new Employee("Alex", "Malash", "[email protected]", new DateTime(1990, 5, 9), allCustomers, allBusiness[0]),
                                            new Employee("Ira", "Vashnko", "[email protected]", new DateTime(1990, 9, 1), new List<Customer> { allCustomers[0] }, allBusiness[1]),
                                            new Employee("Igor", "Loshara", "[email protected]", new DateTime(1990, 1, 8), allCustomers, allBusiness[0])};
    }
}

When I use DataContractSerializer, I can't create attributes, and when I use XmlSerializer, at deserializetion, there are mismatch in the same ojects(Customer) in different employees(there are some different objects with same filds).

what can I try?

Upvotes: 1

Views: 1365

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063824

DataContractSerializer doesn't do attributes, so forget that. You really want XmlSerializer. I'm very unclear what issue you are describing with the ids. I would be very surprised if it deserialized it incorrectly. Perhaps post a repeatable example if you believe that is the case, but it sounds like you simply have data you weren't expecting.

The data is the data, but I wonder if this is because you are expecting a full "graph" deserialize (preserving object references). XmlSerializer is a "tree" serializer, so it will not matter if the same object was serialized 6 times - it will deserialize into 6 different object. There is nothing special / unique that will identify them. Your only option would be to fix them up manually afterwards, by checking for duplicates and replacing them with a single common instance.

To put that in pictures; if you serialize the tree

A

  • B
    • C
  • D
    • C

(same instance under B and D) it will deserialize as:

A

  • B
    • C
  • D
    • E

But simply C and E will be different objects with the same values.

Upvotes: 2

Related Questions