没有将XML元素列为数组

本文关键字:数组 元素 XML | 更新日期: 2023-09-27 18:12:47

我在根节点上列出快照数组时有问题。下面是代码:

[XmlRoot(ElementName = "WebService", DataType = "WebService", IsNullable = false)]
public class WebServiceXmlElement
{
    [XmlArray("Snapshots"), XmlArrayItem(ElementName = "Snapshot", Namespace = XmlNamespaceSettings.DefaultNamespace, IsNullable = true)]
    public NodeSnapshotElement[] Snapshots { get; set; }
}
public class NodeSnapshotElement
{ 
}
[XmlType(TypeName = "CrateSnapshot", Namespace = XmlNamespaceSettings.DefaultNamespace, IncludeInSchema = false)]
public class NodeCreateSnapshot : NodeSnapshotElement
{
    [XmlAttribute(AttributeName = "ID", Namespace = XmlNamespaceSettings.DefaultNamespace)]
    public string ID { get; set; }
}

生成的XML如下:

<WebService xsd:schemaLocation="...">
  <Snapshots/>
</WebService>

应该是:

<WebService xsd:schemaLocation="...">
  <xsd:Snapshots>
    <xsd:Snapshot>...</xsd:Snapshot>
    <xsd:Snapshot>...</xsd:Snapshot>
  </xsd:Snapshots>
</WebService>

没有将XML元素列为数组

快照数组必须为空。否则将实际生成元素。

注意-你需要为NodeCreateSnapshot类添加XmlInclude声明,否则你会得到一个运行时异常。你可以这样添加:

[XmlRoot(ElementName = "WebService", DataType = "WebService", IsNullable = false)]
[XmlInclude(typeof(NodeCreateSnapshot))]
public class WebServiceXmlElement
{
    // ...
}