3

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, the variable s will hold a value like,

<?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 need to do is, changing the xml array root element 'ArrayOfHuman' to something like 'MyFavoriteArrayRootName'. I have seen the IXmlSerializable interface but, that skips the root element name. Anybody has got any idea how to achieve this?

All comments will be greatly appreciated.

Best regards.

3 Answers 3

2

new keyword was missing before XmlRootAttribute.

XmlSerializer xs = new XmlSerializer(
    typeof(Human[]), new XmlRootAttribute("MyFavoriteArrayRootName"));
Sign up to request clarification or add additional context in comments.

Comments

0

try

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

Comments

0

Put the XmlRoot on your Human class like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.