Home >Backend Development >C++ >How to Suppress the Root Array Element in XML Serialization?
XML Serialization: Suppressing Root Array Element
Question:
Can serialization of an XML collection's root element be disabled? Consider the following class with attributes:
[XmlRoot(ElementName="SHOPITEM", Namespace="")] public class ShopItem { [XmlElement("PRODUCTNAME")] public string ProductName { get; set; } [XmlArrayItem("VARIANT")] public List<ShopItem> Variants { get; set; } }
This class generates XML with a root
<SHOPITEM xmlns:xsi="" xmlns:xsd=""> <PRODUCTNAME>test</PRODUCTNAME> <Variants> <VARIANT> <PRODUCTNAME>hi 1</PRODUCTNAME> </VARIANT> <VARIANT> <PRODUCTNAME>hi 2</PRODUCTNAME> </VARIANT> </Variants> </SHOPITEM>
How can
Answer:
To eliminate the
[XmlRoot("SHOPITEM")] public class ShopItem { [XmlElement("PRODUCTNAME")] public string ProductName { get; set; } [XmlElement("VARIANT")] // was [XmlArrayItem] public List<ShopItem> Variants { get; set; } }
To remove the xsi and xsd namespaces, create an XmlSerializerNamespaces instance with an empty namespace and use it during serialization:
// ... ShopItem item = new ShopItem() { ProductName = "test", ... }; // This removes the xsi/xsd namespaces from serialization XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer ser = new XmlSerializer(typeof(ShopItem)); ser.Serialize(Console.Out, item, ns); // Pass XmlSerializerNamespaces here
The resulting XML will have the desired format:
<?xml version="1.0" encoding="ibm850"?> <SHOPITEM> <PRODUCTNAME>test</PRODUCTNAME> <VARIANT> <PRODUCTNAME>hi 1</PRODUCTNAME> </VARIANT> <VARIANT> <PRODUCTNAME>hi 2</PRODUCTNAME> </VARIANT> </SHOPITEM>
The above is the detailed content of How to Suppress the Root Array Element in XML Serialization?. For more information, please follow other related articles on the PHP Chinese website!