Home > Backend Development > C++ > How to Suppress the Root Array Element in XML Serialization?

How to Suppress the Root Array Element in XML Serialization?

Patricia Arquette
Release: 2024-12-31 18:30:10
Original
912 people have browsed it

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; }
}
Copy after login

This class generates XML with a root element:

<SHOPITEM xmlns:xsi="" xmlns:xsd="">
  <PRODUCTNAME>test</PRODUCTNAME>
  <Variants>
    <VARIANT>
      <PRODUCTNAME>hi 1</PRODUCTNAME>
    </VARIANT>
    <VARIANT>
      <PRODUCTNAME>hi 2</PRODUCTNAME>
    </VARIANT>
  </Variants>
</SHOPITEM>
Copy after login

How can be omitted from the output? Additionally, how can the xsi and xsd namespaces be removed from the root element?

Answer:

To eliminate the element, replace the [XmlArrayItem] attribute with [XmlElement] for the collection property:

[XmlRoot("SHOPITEM")]
public class ShopItem
{
    [XmlElement("PRODUCTNAME")]
    public string ProductName { get; set; }

    [XmlElement("VARIANT")] // was [XmlArrayItem]
    public List<ShopItem> Variants { get; set; }
}
Copy after login

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
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template