Yes, as Chiso 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 serialization (approximately) works based on the fact that:
- The serializable object decides how its contents are serialized (including attributes of the root element)
- However, the caller is responsible for creating the root element (and its use in deserialization).
You can see this because of how the IXmlSerializable interface IXmlSerializable . A serializable object can use the XmlRootAttribute attribute as a suggestion to the caller about what the root element should look like, but ultimately it depends on the caller to create the root element (usually using the XmlSerializer class).
source share