plh
plh

Reputation: 45

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 looks like this

<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 get the 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 type Audit'

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

Thanks

Upvotes: 3

Views: 302

Answers (2)

Buggie
Buggie

Reputation: 122

I agree with giammin's answer, and it works. If you want to leave the id nullable, then I would suggest just removing the attribute above Id. You'll get an output simiar 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

Upvotes: 0

giammin
giammin

Reputation: 18958

Add Serializable attribute to class ValueWithId

[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'll find it quite eloquent:

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

if you need to serialize a nullable look there: Serialize a nullable int

Upvotes: 1

Related Questions