Get rid of root element when serializing array

后端 未结 2 1894
小鲜肉
小鲜肉 2021-01-19 21:08

Here\'s a code example:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

...

相关标签:
2条回答
  • 2021-01-19 21:43

    IMO you should use a top-level object, I.e.

    [XmlRoot("whatever")]
    public class Foo {
        [XmlElement("Person")]
        public List<Person> People {get;set;}        
    }
    

    Which should serialize as a "whatever" element with multiple "Person" sub-elements.

    0 讨论(0)
  • 2021-01-19 22:01

    That's a malformed XML you want, not possible to obtain it via XmlSerializer, but you can change ArrayOfPersno element name to smothing else:

    example:

    XmlSerializer xs = new XmlSerializer(typeof(Person[]),
                                         new XmlRootAttribute("Persons"));
    

    will give you:

    <?xml version="1.0"?>
    <Persons xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Person>
        <FirstName>John</FirstName>
        <LastName>Smith</LastName>
      </Person>
      ...
    
    0 讨论(0)
提交回复
热议问题