C# Xml serialization, collection and root element

前端 未结 3 603
攒了一身酷
攒了一身酷 2020-12-17 18:16

My app serializes objects in streams. Here is a sample of what I need :


  
  

        
3条回答
  •  忘掉有多难
    2020-12-17 18:46

    XmlSerializer should be able to do what you need, but it is highly dependent on the initial structure and setup. I use it in my own code to generate remarkably similar things.

    public class Links : BaseArrayClass //use whatever base collection extension you actually need here
    {
        //...stuff...//
    }
    
    public class Link
    {
        [XmlAttribute("href")]
        public string Url { get; set; }
    
        [XmlAttribute("rel")]
        public string Relationship { get; set; }
    }
    

    now, serializing the Links class should generate exactly what you are looking for.

    The problem with XmlSerializer is when you give it generics, it responds with generics. List implemets Array somewhere in there and the serialized result will nearly always be ArrayOf. To get around that you can name the property, or the class root. The closes to what you need is probably the Second Version from your examples. Im assuming you attempted direct serialization of an object List Links. That wouldn't work because you didn't specify the root node. Now, a similar approach can be found here. In this one they specify the XmlRootAttribute when declaring the serializer. yours would look like this:

    XmlSerializer xs = new XmlSerializer(typeof(List), new XmlRootAttribute("Links"));
    

提交回复
热议问题