XML 序列化 - 禁用呈现数组的根元素 [英] XML Serialization - Disable rendering root element of array

查看:32
本文介绍了XML 序列化 - 禁用呈现数组的根元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以以某种方式禁用集合根元素的渲染吗?

Can I somehow disable rendering of root element of collection?

这个具有序列化属性的类:

This class with serialization attributes:

[XmlRoot(ElementName="SHOPITEM", Namespace="")]
public class ShopItem
{
    [XmlElement("PRODUCTNAME")]
    public string ProductName { get; set; }       
    
    [XmlArrayItem("VARIANT")]
    public List<ShopItem> Variants { get; set; }
}

生成此 XML:

<SHOPITEM xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <PRODUCTNAME>test</PRODUCTNAME>
      <Variants>
          <VARIANT>
              <PRODUCTNAME>hi 1</PRODUCTNAME>
          </VARIANT>
          <VARIANT>
              <PRODUCTNAME>hi 2</PRODUCTNAME>
          </VARIANT>           
      </Variants>        
</SHOPITEM>

我不想要 元素在这里.我该怎么办?

I don't want <Variants> element here. What must I do?

此外,我不需要根元素中的 xsi 和 xsd 命名空间...

Also I don't need xsi and xsd namespaces in root element...

推荐答案

要禁用集合的根元素的呈现,您必须将属性 [XmlArrayItem] 替换为 [XmlElement] 在您的代码中.

To disable rendering of root element of collection, you must replace the attribute [XmlArrayItem] with [XmlElement] in your code.

要删除 xsixsd 命名空间,请创建一个带有空命名空间的 XmlSerializerNamespaces 实例,并在需要序列化对象时传递它.

For removing the xsi and xsd namespaces, create an XmlSerializerNamespaces instance with an empty namespace and pass it when you need to serialize your object.

看看这个例子:

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

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

// ...

ShopItem item = new ShopItem()
{
    ProductName = "test",
    Variants    = new List<ShopItem>()
    {
        new ShopItem{ ProductName = "hi 1" },
        new ShopItem{ ProductName = "hi 2" }
    }
};

// This will remove the xsi/xsd namespaces from serialization
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");

XmlSerializer ser = new XmlSerializer(typeof(ShopItem));
ser.Serialize(Console.Out, item, ns);  // Inform the XmlSerializerNamespaces here

我得到了这个输出:

<?xml version="1.0" encoding="ibm850"?>
<SHOPITEM>
  <PRODUCTNAME>test</PRODUCTNAME>
  <VARIANT>
    <PRODUCTNAME>hi 1</PRODUCTNAME>
  </VARIANT>
  <VARIANT>
    <PRODUCTNAME>hi 2</PRODUCTNAME>
  </VARIANT>
</SHOPITEM>

这篇关于XML 序列化 - 禁用呈现数组的根元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆