我可以以某种方式禁用集合根元素的渲染吗?
此类具有序列化属性:
[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>
我不要<Variants>在这里元素。我必须做什么?
<Variants>
另外我在根元素中不需要xsi和xsd命名空间…
要收集的根元素的渲染禁用,则必须更换属性[XmlArrayItem]用[XmlElement]在你的代码。
[XmlArrayItem]
[XmlElement]
要删除xsi和xsd名称空间,请创建一个XmlSerializerNamespaces具有空名称空间的实例,并在需要序列化对象时将其传递。
xsi
xsd
XmlSerializerNamespaces
看一下这个例子:
[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>