简体   繁体   中英

Is it possible to serialize objects made from different class in the same xml file?

For example, I got the class Header , and the class Dog . I would like a file that looks like this:

在此处输入图片说明

So far, I have seen no examples to perform this. I must use the serializer.Serialize because I got a collection of thousands of objects. Doing otherwise would take too long.

If it is impossible, I will make two different files, one with the header and the other with the collection of objects, but it is not an interesting solution.

Edit:
I can't use a wrapper since I don't have my complete dog list at the beginning. I receive one at the time until I stop the application

Thanks a lot!

You will need to create another class the can represent this. For example.

public class Kennel
{
    public Header Header { get; set; }
    public List<Dog> Dogs { get; set; }
}

This can then be serialized/deserialized easily.

In answer to your question. If you need the XML to be identical to yours, you will need to create a custom wrapper that will read and write the XML into that specific format.

I would looking at making a custom wrapper class (call it: DogWrapper or something) that contained a Header object and a list (or array, or whatever) of type Dog . Then use custom serialization to define how to write out that object.

Then you just marshal your header and dogs into a DogWrapper, and serialize the DogWrapper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM