|
-
April 26th, 2011, 07:56 AM
#1
Help with Serializing an Array of a custom object
Very straight forward but am drawing blanks. Been googling for the last day and a half and haven't found a good example that I can use to make work.
Code:
[XmlRoot(Namespace = "http://mynamespace.com")]
public class Documents
{
[XmlArray]
[XmlArrayItem(typeof(Document))]
public ArrayList MyDocuments { get; set; }
public void Add(Document document)
{
MyDocuments.Add(document);
}
}
public class Document
{
[XmlElement]
public int id { get; set; }
[XmlElement]
public string name { get; set; }
}
I want it to output like this:
<?xml version="1.0"?>
<Documents xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://mynamespace.com">
<Document>
<id>1</id>
<name>greg</name>
</Document>
<id>2</id>
<name>jeff</name>
<Document>
</Document>
</Documents>
And here's the main part of just creating the document:
Code:
Documents myDocs = new Documents();
Document myDoc1 = new Document();
myDoc1.id = 1;
myDoc1.name = "greg";
myDocs.Add(myDoc1);
Document myDoc2 = new Document();
myDoc2.id = 2;
myDoc2.name = "jeff";
myDocs.Add(myDoc2);
// Make call to serialize here...
Right now I'm getting an error on the Add method saying it needs a new keyword.
Anyone have any suggestions?
Last edited by andegre; April 26th, 2011 at 07:59 AM.
-
April 26th, 2011, 01:16 PM
#2
Re: Help with Serializing an Array of a custom object
A couple of things.
Your MyDocuments starts it life being null and so the call to Add will create an error becuase MyDocuments is not initialised.
Also, I do believe that XmlSerialisation requires a default constructor in order for it to work and so you should probably put it in explicitly.
Code:
[XmlRoot(Namespace = "http://mynamespace.com")]
public class Documents
{
public Documents()
{
//Default Constructor for Xml Serialisation
}
[XmlArray]
[XmlArrayItem(typeof(Document))]
public ArrayList MyDocuments { get; set; }
public void Add(Document document)
{
if (MyDocuments == null)
{
MyDocuments = new ArrayList();
}
MyDocuments.Add(document);
}
}
public class Document
{
public Document()
{
//Default Constructor for Xml Serialisation
}
[XmlElement]
public int id { get; set; }
[XmlElement]
public string name { get; set; }
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|