Adding Attributes When Serializing to XML

I have this class

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; }
}

      

When I serialize it it looks like

<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>

      

I added this class to try and get id fields as attribute

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

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

      

Rewrote my class to this

[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; }
}

      

But I get the error "There was an error reflecting the type" Audit "

I am trying to get the following as 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>

      

thank

+3


source to share


2 answers


Add attribute Serializable

to classValueWithId

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

   [XmlText] 
   public string Description { get; set; }
}

      

and if you look at your exception, you find it quite eloquent:



"Unable to serialize element 'Id' of type System.Nullable`1 [System.Int64]. XmlAttribute / XmlText cannot be used to encode complex types." }

if you need to serialize a nullable view: Serialize nullable int

+1


source


I agree with giammin's answer and it works. If you want to leave id nullable, I would suggest just removing the attribute above Id. You will get a result similar to this:

<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>

      



Otherwise, I don't believe it can serialize nullable types

0


source







All Articles