473,401 Members | 2,125 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,401 software developers and data experts.

deserialize a collection

I'm writing a class in C# ....
I have a collection calls Reports made up of Report objects. I'm trying to deserialize an XML file that looks like :
<Reports>
<Report>
<Title>some title</Title>
<Notes> some notes </Notes>
</Report>
<Report>
blah blah blah
</Report>
</Reports>

-------------------------------------------------------------------
I want to be able to deserialize the file in the Reports collection constructor and build the Report objects on the fly. The only examples I've been able to find read the entire XML file outside of the class (which works fine in my test console app), but I want to be able to be able to dynamically build everything inside the collection class. Do I need to parse through the XML file and got to each <Report> tag and deserialize one Report at a time (and use "this.Add(newReport)")? How can parse the file like that and pass just that info into the deserialize method? I haven't used XPath, so if I need that, an example would really help.
Nov 12 '05 #1
2 9503
XmlSerializer serializer = new XmlSerializer(typeof(Report));
ArrayList reportList = new ArrayList();
XmlNode reports = ???; // XPath is good here if you've got a document
rather than a source node or are pulling from a DB
foreach (XmlNode report in reports.ChildNodes) {
if (!(report is XmlElement)) {
continue;
}
reportList.Add(serializer.Deserialize(new XmlNodeReader(report)));
}
"Greg" <Gr**@discussions.microsoft.com> wrote in message
news:98**********************************@microsof t.com...
I'm writing a class in C# ....
I have a collection calls Reports made up of Report objects. I'm trying to deserialize an XML file that looks like : <Reports>
<Report>
<Title>some title</Title>
<Notes> some notes </Notes>
</Report>
<Report>
blah blah blah
</Report>
</Reports>

-------------------------------------------------------------------
I want to be able to deserialize the file in the Reports collection

constructor and build the Report objects on the fly. The only examples I've
been able to find read the entire XML file outside of the class (which works
fine in my test console app), but I want to be able to be able to
dynamically build everything inside the collection class. Do I need to
parse through the XML file and got to each <Report> tag and deserialize one
Report at a time (and use "this.Add(newReport)")? How can parse the file
like that and pass just that info into the deserialize method? I haven't
used XPath, so if I need that, an example would really help.
Nov 12 '05 #2
for an alternative approach in which you do not iterate on the XML or on
each item, see the example below.

-Dino
// reports.cs
//
// build with:
// csc /target:exe /out:a.exe reports.cs
//
// Sat, 17 Jul 2004 15:23
//

using System.Xml.Serialization;

namespace Ionic {

public class Report {

[System.Xml.Serialization.XmlElementAttribute(Form= System.Xml.Schema.XmlSche
maForm.Unqualified)]
public string Title;

[System.Xml.Serialization.XmlElementAttribute(Form= System.Xml.Schema.XmlSche
maForm.Unqualified)]
public string Notes;
[System.Xml.Serialization.XmlText]
public string Something;
}

[System.Xml.Serialization.XmlRoot("Reports", Namespace="",
IsNullable=false)]
[System.Xml.Serialization.XmlType("Reports", Namespace="")]
public class ReportCollection {
[System.Xml.Serialization.XmlElementAttribute("Repo rt",
Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public Report[] Items;

public ReportCollection() {
// null constructor must not de-serialize, else you get an endless
loop (stack overflow)
}

// one approach is to use a parameterized constructor.
// this param in this case is an xml string, but it need not be.
// it could be the name of an XML file, a stream, whatever.
public ReportCollection(string s) {
ReportCollection temp= ReportCollection.CreateFromString(s);
Items= temp.Items; // shallow copy of array. Would need to do this
for each field in the RC type
// "temp" now goes out of scope but the Items array gets referenced by
"this"
}
// another approach: use a public static factory method.
// user could call as above (as shown in the parameterized constructor)
public static ReportCollection CreateFromString(string xml1) {
// could parameterize this with a filename, a stream, a string,
whatever
XmlSerializer s1 = new XmlSerializer(typeof(ReportCollection));

// slurp it in: deserialize the original XML into a value
System.IO.StringReader sr= new System.IO.StringReader(xml1);
ReportCollection rc= (ReportCollection) s1.Deserialize(new
System.Xml.XmlTextReader(sr));

return rc;
}
}
public class TestDriver {

static void Main(string[] args) {

string xml1=
"<Reports>\n" +
" <Report>\n" +
" <Title>some title</Title>\n" +
" <Notes> some notes </Notes>\n" +
" </Report>\n" +
" <Report>\n" +
" blah blah blah\n" +
" </Report>\n" +
"</Reports>\n" +
"";

// Show the original XML

System.Console.WriteLine("\n====================== ======================\n\n
\nSource XML:\n{0}", xml1);

// spit it out: show the value we got
System.Console.WriteLine("\n\n\nDe-serialize then Serialize to
System.Console.Out:\n");

ReportCollection rc= new ReportCollection(xml1);
// could also use the factory method:
// ReportCollection rc= ReportCollection.CreateFromString(xml1);

XmlSerializer s1 = new XmlSerializer(typeof(ReportCollection));

// use this to "suppress" the default xsd and xsd-instance namespaces
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add( "", "" );
s1.Serialize(System.Console.Out, rc, ns);

System.Console.WriteLine("\n\n");

}
}
}

"Keith Patrick" <ri*******************@nospamhotmail.com> wrote in message
news:%2***************@TK2MSFTNGP10.phx.gbl...
XmlSerializer serializer = new XmlSerializer(typeof(Report));
ArrayList reportList = new ArrayList();
XmlNode reports = ???; // XPath is good here if you've got a document
rather than a source node or are pulling from a DB
foreach (XmlNode report in reports.ChildNodes) {
if (!(report is XmlElement)) {
continue;
}
reportList.Add(serializer.Deserialize(new XmlNodeReader(report)));
}
"Greg" <Gr**@discussions.microsoft.com> wrote in message
news:98**********************************@microsof t.com...
I'm writing a class in C# ....
I have a collection calls Reports made up of Report objects. I'm trying to deserialize an XML file that looks like :
<Reports>
<Report>
<Title>some title</Title>
<Notes> some notes </Notes>
</Report>
<Report>
blah blah blah
</Report>
</Reports>

-------------------------------------------------------------------
I want to be able to deserialize the file in the Reports collection

constructor and build the Report objects on the fly. The only examples

I've been able to find read the entire XML file outside of the class (which works fine in my test console app), but I want to be able to be able to
dynamically build everything inside the collection class. Do I need to
parse through the XML file and got to each <Report> tag and deserialize one Report at a time (and use "this.Add(newReport)")? How can parse the file
like that and pass just that info into the deserialize method? I haven't
used XPath, so if I need that, an example would really help.

Nov 12 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: jamie_m_ | last post by:
I have a custom collection ... clFile that INHERITS from NameObjectCollectionBase the problem is, when I try to create an xmlserializer instance i get an error You must implement a default...
1
by: Brian Orrell | last post by:
I know how to deserialize a collection class that is referenced in a container class as a variable or property using the XmlArray and XmlArrayItem attributes. What I can't for the life of me...
0
by: Just D. | last post by:
There is an interesting article - http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=542&printer=t It shows how to serialize the ArrayList of identical objects. I did it a year...
1
by: Mark Overstreet | last post by:
Hi, I have several custom collections that inherit from System.Collections.Specialized.NameObjectCollectionBase and I want to serialize and deserialize with the XMLSerializer object. This works...
2
by: Islamegy® | last post by:
I have started to implement Strongly typed CustomCollection for my Entities instead of using Dataset & Datatable.. All my Collection Classes inherit from CollectionBase.. I tried to serialize my...
16
by: Ben Hannon | last post by:
Hi, I'm writting a COM Class in VB.NET to be used in a VB6 project (Tired of the VB6 hassles with cloning and serializing an object). All my classes I need cloneable/serializable are now in a...
4
by: Michael Rich | last post by:
Can anyone point me to a collection class that has serialization/deserialization with it - preferably in XML. I know this can't be done with a collection that inherits from CollectionBase, but...
0
by: Tom P | last post by:
I'm using System.Configuration in .NET 2.0 to load in values from an externally specified config file and deserialize them into a C# class. During deserialization, I'm getting an exception thrown...
1
by: Martin Z | last post by:
I'm getting acquainted with the whole XML/XSD thing, and I've run into a wall. I have a tree of objects that I deserialize from XML for configuration reasons. I have generated XSD from the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.