开发者

C# Controlling element name when serialising to XML

开发者 https://www.devze.com 2023-03-06 14:34 出处:网络
I have a class that I want to serialise to XML. The name of outer element of the class when serialised needs to be controlled by the application.

I have a class that I want to serialise to XML. The name of outer element of the class when serialised needs to be controlled by the application.

At design time I know the element name can be controlled by the use an XmlTypeAttribute

 [XmlElement(Name="MyName")]

I n开发者_JAVA百科eed to control this at run time so this will not work for me.

I also looked at IXmlSerializable to create my own serialisation code, but again this will not work as this only allows control of the 'internals' of the class and not the external wrapper.

Are there any other options available?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消