How to change array element names in XmlSerialization?

Consider the following code:

[Serializable]
public class Human
{
    public string Name { get; set; }
}

Then

        using (MemoryStream ms = new MemoryStream())
        {   
            Human[] mans = new Human[] { 
                new Human() { Name = "Moim" }
                    };

            XmlSerializer xs = new XmlSerializer(typeof(Human[]));
            xs.Serialize(ms, mans);
            string s = System.Text.ASCIIEncoding.ASCII.GetString(ms.ToArray());
        }

At this point, s will contain a value similar to

<?xml version="1.0"?>
<ArrayOfHuman xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Human>
    <Name>Moim</Name>
  </Human>
</ArrayOfHuman>

Now all I have to do is change the root element of the xml ArrayOfHuman array to something like "MyFavoriteArrayRootName". I saw the IXmlSerializable interface, but that skips the name of the root element. Does anyone know how to achieve this?

All comments would be greatly appreciated.

Sincerely.

+3
source share
3 answers

to try

XmlSerializer xs = new XmlSerializer(typeof(Human[]), XmlRootAttribute("MyFavoriteArrayRootName"));
0
source
XmlRootAttribute missing keyword

new .

XmlSerializer xs = new XmlSerializer(
    typeof(Human[]), new XmlRootAttribute("MyFavoriteArrayRootName"));
+2
source

XmlRoot Human :

[Serializable]
[XmlRoot("MyFavoriteArrayRootName")]
public class Human
{
    public string Name { get; set; }
}
0

Source: https://habr.com/ru/post/1741282/


All Articles