XML Serialization structure

前端 未结 2 1447
说谎
说谎 2021-01-26 05:18

Apologies on not being able to phrase the title more specifically but I can only explain by giving an example.

I\'m trying to build a class that serializes to the follow

相关标签:
2条回答
  • 2021-01-26 05:39

    Use XmlElementAttribute to mark your collection properties.

    public class Customize
    {
        [XmlElement("Content")]
        public List<Content> Content { get; set; }
    
        [XmlElement("Command")]
        public List<Command> Command { get; set; }
    }
    

    Quick test code:

    var item = new Customize() { Content = new List<Content> { new Content(), new Content() }, Command = new List<Command> { new Command(), new Command(), new Command() } };
    
    string result;
    
    using (var writer = new StringWriter())
    {
        var serializer = new XmlSerializer(typeof(Customize));
        serializer.Serialize(writer, item);
        result = writer.ToString();
    }
    

    Prints:

    <?xml version="1.0" encoding="utf-16"?>
    <Customize xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Content />
      <Content />
      <Command />
      <Command />
      <Command />
    </Customize>
    
    0 讨论(0)
  • 2021-01-26 05:48
    public class Customize
    {
        [XmlElement("Content")]
        public List<Content> Content { get; set; }
    
        [XmlElement("Command")]
        public List<Command> Command { get; set; }
    }
    
    0 讨论(0)
提交回复
热议问题