Yes, as Cheeso pointed out in the comments you can do this using XmlAttributeOverrides
XmlAttributes overrideAttributes = new XmlAttributes();
overrideAttributes.XmlRoot = new XmlRootAttribute("Testing");
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(typeof(string[]), overrideAttributes);
XmlSerializer serialise = new XmlSerializer(typeof(string[]), overrides);
using (MemoryStream stream = new MemoryStream())
{
serialise.Serialize(stream, new string[] { Guid.NewGuid().ToString(), Guid.NewGuid().ToString() });
}
Output:
<?xml version="1.0"?>
<Testing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>37d47837-62d0-46dc-9747-709b91bdac6e</string>
<string>9cd904a9-f86f-46c1-a2aa-49c44bc3c654</string>
</Testing>
Xml serialisation (roughly) works on the basis that:
- The object being serialised decides how its contents are serialised (including attributes of the root element)
- However the caller is responsible for creating the root element (and consuming it on deserialisation).
You can see this from the way that the IXmlSerializable interface works - The object being serialised can use the XmlRootAttribute attribute as a suggestion to the caller on what the root element should look like, however ultimately it is up to the caller to create the root element (normally hanled by the XmlSerializer class).
[XmlElement(MyClass.ElementName)]. I didn't post this as an answer since I'm not sure it will work correctly.