C # Managing element name when serializing in XML

I have a class that I want to serialize to XML. The name of the external element of the class during serialization must be controlled by the application.

During development, I know that the name of the element can be controlled using XmlTypeAttribute

[XmlElement(Name="MyName")] 

I need to manage this at runtime so that it doesn't work for me.

I also looked at IXmlSerializable to create my own serialization code, but again this will not work, as this allows you to control only the "internals" of the class, and not the outer shell.

Are there any other options available?

+4
source share
1 answer

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).

+2
source

All Articles