【问题标题】:Adding attributes when serializing to XML序列化为 XML 时添加属性
【发布时间】:2013-01-28 02:11:51
【问题描述】:

我有这门课

public class Audit
{
   public string name { get; set;}
   public DateTime AuditDate { get; set;}

   public long? DepartmentId  {get; set;}
   public string Department { get; set;}

   public long? StateId { get; set;}
   public string? State { get; set; }

   public long? CountryId { get; set; }
   public string Country { get; set; }
}

当我序列化时它看起来像这样

<Audit>
    <name>George</name>
    <AuditDate>01/23/2013</AuditDate>
    <DepartmentId>10</DepartmentId>
    <Department>Lost and Found</Department>
    <StateId>15</StateId>
    <State>New Mexico</StateId>
    <CountryId>34</CountryId>
    <Country>USA</Country>
</Audit>

我添加了这个类来尝试获取 id 字段作为属性

public class ValueWithId
{
   [XmlAttribute ("id")]
   public long? Id { get; set; }

   [XmlText]  // Also tried with [XmlElement]
   public string Description { get; set; }
}

把我的课改写成这个

[Serializable]
public class Audit
{
    public string name { get; set;}
    public DateTime AuditDate { get; set;}

    public ValueWithId Department { get; set;}
    public ValueWithId State { get; set; }
    public ValueWithId Country { get; set; }
}

但我收到错误“反映类型审核时出现错误”

我正在尝试将以下内容作为 XML

<Audit>
   <name>George</name>
   <AuditDate>01/23/2013</AuditDate>
   <Department id=10>Lost and Found</Department>
   <State id=15>New Mexico</State>
   <Country id=34>USA</Country>
</Audit>

谢谢

【问题讨论】:

    标签: c# xml xml-serialization


    【解决方案1】:

    Serializable属性添加到类ValueWithId

    [Serializable]
    public class ValueWithId
    {
       [XmlAttribute ("id")]
       public long Id { get; set; }
    
       [XmlText] 
       public string Description { get; set; }
    }
    

    如果你看一下你的异常,你会发现它很有说服力:

    “无法序列化 System.Nullable`1[System.Int64] 类型的成员 'Id'。 XmlAttribute/XmlText 不能用于编码复杂类型。"}

    如果您需要在此处序列化可为空的外观: Serialize a nullable int

    【讨论】:

    • 我仍然收到错误“反映类型审核时出现错误”
    • 谢谢。就是这样,我的 id 可以为空。
    【解决方案2】:

    我同意 giammin 的回答,并且有效。如果您想让 id 可以为空,那么我建议您只删除 Id 上方的属性。您将获得与此类似的输出”:

    <Audit xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <name>George</name>
        <AuditDate>2013-01-23T00:00:00</AuditDate>
        <Department>
        <Id>10</Id>Lost and Found</Department>
        <State>
        <Id>15</Id>New Mexico</State>
        <Country>
        <Id>34</Id>USA</Country>
    </Audit>
    

    否则,我不相信它可以序列化可空类型

    【讨论】:

      猜你喜欢
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多