问题描述
我可以以某种方式禁用集合根元素的渲染?
Can I somehow disable rendering of root element of collection?
本类序列化属性:
[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>
我不希望&LT;变形例&GT;
元素在这里。我必须做什么?
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]
在code。
To disable rendering of root element of collection, you must replace the attribute [XmlArrayItem]
with [XmlElement]
in your code.
有关删除 XSI
和 XSD
命名空间,创建一个 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
我得到这样的输出:
I got this output:
<?xml version="1.0" encoding="ibm850"?>
<SHOPITEM>
<PRODUCTNAME>test</PRODUCTNAME>
<VARIANT>
<PRODUCTNAME>hi 1</PRODUCTNAME>
</VARIANT>
<VARIANT>
<PRODUCTNAME>hi 2</PRODUCTNAME>
</VARIANT>
</SHOPITEM>
这篇关于XML序列化 - 阵列禁止渲染根元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!