473,756 Members | 2,900 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

serialize 2 objects to same xml file?

Can I add (append) to an xml file that already contains a
serialized object, and be able to deserialize to either
or both objects from the same file...??? How is this
done...??

thanks,

vince
Nov 15 '05
14 14310
> .... in microsoft.publi c.dotnet.genera l.

Correction: microsoft.publi c.dotnet.vb
Nov 15 '05 #11
Robert,

tried your suggestion of putting the 2 serializable
objects into an Arraylist, and also an array of type
object[], but I get runtime errors... here's the code:

object[] jobArray = new object[2];

jobArray[0] = theJob; //serializable custom type w/
arraylist
jobArray[1] = myTask; //arraylist
XmlSerializer x2 = new XmlSerializer(t ypeof(object[]));
TextWriter tw = new StreamWriter("c :\\backup\\" +
textBox1.Text + ".xml");

x2.Serialize(tw , jobArray);

The exception thrown is "Job.JobFil e may not be used in
this context".... Job is the namespace, and theJob is an
object of type Job.JobFile.

Did the same thing using an Arraylist to hold the two
objects with similar results...

Thanks for any further suggestions... sorry for the
double post on newsgroups..

-----Original Message-----
Vince,

I replied to your question in microsoft.publi c.dotnet.genera l. In thefuture, please don't repost the same question to multiple groups.
There's no need to use strange workarounds to get this done. Just define anarray of objects (or ArrayList, or strongly-typed collection), place bothitems in the array, and serialize/deserialize the array. It will work fine.
--Robert Jacobson

"vince" <vl******@sdcer a.org> wrote in message
news:00******* *************** ******@phx.gbl. ..
Can I add (append) to an xml file that already contains a serialized object, and be able to deserialize to either
or both objects from the same file...??? How is this
done...??

thanks,

vince

.

Nov 15 '05 #12
Robert,

I would also add that theJob seriailizes fine
individually, but I can't seem to get it to do so when
it's an element of a parent container...

thanks for your time...

vince
-----Original Message-----
Robert,

tried your suggestion of putting the 2 serializable
objects into an Arraylist, and also an array of type
object[], but I get runtime errors... here's the code:

object[] jobArray = new object[2];

jobArray[0] = theJob; //serializable custom type w/
arraylist
jobArray[1] = myTask; //arraylist
XmlSerialize r x2 = new XmlSerializer(t ypeof(object[]));
TextWriter tw = new StreamWriter("c :\\backup\\" +
textBox1.Tex t + ".xml");

x2.Serialize(t w, jobArray);

The exception thrown is "Job.JobFil e may not be used in
this context".... Job is the namespace, and theJob is an
object of type Job.JobFile.

Did the same thing using an Arraylist to hold the two
objects with similar results...

Thanks for any further suggestions... sorry for the
double post on newsgroups..

-----Original Message-----
Vince,

I replied to your question in

microsoft.publ ic.dotnet.gener al. In the
future, please don't repost the same question to

multiple groups.

There's no need to use strange workarounds to get this

done. Just define an
array of objects (or ArrayList, or strongly-typed

collection), place both
items in the array, and serialize/deserialize the

array. It will work fine.

--Robert Jacobson

"vince" <vl******@sdcer a.org> wrote in message
news:00****** *************** *******@phx.gbl ...
Can I add (append) to an xml file that alreadycontains a serialized object, and be able to deserialize to either or both objects from the same file...??? How is this
done...??

thanks,

vince

.

.

Nov 15 '05 #13
You're right -- it turns out you can't just stuff an Object[] array with
custom classes and expect it to serailize correctly. The reason is that the
XmlSerializer is kind of dumb... it needs to know what type of object is
being stored in the array so that it can deserialize it correctly later on.
Sorry for leading you astray. <g>

The easiest way around this is to use a strongly-typed array or collection.
So, it should work if you replace the line "object[] jobArray = new
object[2];" with "jobFile[] jobArray = new jobFile[2];" I have some sample
code below. Alternatively, you could define a strongly-typed JobFile
collection by inheriting from CollectionBase.

Another alternative is to use the SOAP serializer or binary serializer
instead. Both are more robust than the XmlSerializer, and should be able to
serialize Object[] arrays correctly. The tradeoff is that the output from
those serializers are not as easily readable (for human eyes) than the clean
XML generated by the XmlSerailizer. Check out these articles:

http://msdn.microsoft.com/library/de...bjserializ.asp
http://msdn.microsoft.com/library/de...et09252001.asp

Hope this helps,
Robert Jacobson
using System;
using System.Xml.Seri alization;
using System.IO;
using System.Diagnost ics;

namespace ConsoleApplicat ion1
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
SerializationTe st();
}

static void SerializationTe st()
{
Object[] jobArray = new Object[2];

DummyJob job1 = new DummyJob();
job1.Name = "First Job";
jobArray[0] = job1;

DummyJob job2 = new DummyJob();
job2.Name = "Second Job";
jobArray[1] = job2;

try
{

XmlSerializer serializer = new XmlSerializer(j obArray.GetType ());
StreamWriter sw = new StreamWriter("T est.xml");

serializer.Seri alize(sw, jobArray);
sw.Close();
}
catch (Exception ex)
{
Debug.WriteLine (ex.ToString()) ;
}
}
}

public class DummyJob
{
public string Name;
}

}
"vince" <vl******@sdcer a.org> wrote in message
news:02******** *************** *****@phx.gbl.. .
Robert,

I would also add that theJob seriailizes fine
individually, but I can't seem to get it to do so when
it's an element of a parent container...

thanks for your time...

vince
-----Original Message-----
Robert,

tried your suggestion of putting the 2 serializable
objects into an Arraylist, and also an array of type
object[], but I get runtime errors... here's the code:

object[] jobArray = new object[2];

jobArray[0] = theJob; //serializable custom type w/
arraylist
jobArray[1] = myTask; //arraylist
XmlSerialize r x2 = new XmlSerializer(t ypeof(object[]));
TextWriter tw = new StreamWriter("c :\\backup\\" +
textBox1.Tex t + ".xml");

x2.Serialize(t w, jobArray);

The exception thrown is "Job.JobFil e may not be used in
this context".... Job is the namespace, and theJob is an
object of type Job.JobFile.

Did the same thing using an Arraylist to hold the two
objects with similar results...

Thanks for any further suggestions... sorry for the
double post on newsgroups..

-----Original Message-----
Vince,

I replied to your question in

microsoft.publ ic.dotnet.gener al. In the
future, please don't repost the same question to

multiple groups.

There's no need to use strange workarounds to get this

done. Just define an
array of objects (or ArrayList, or strongly-typed

collection), place both
items in the array, and serialize/deserialize the

array. It will work fine.

--Robert Jacobson

"vince" <vl******@sdcer a.org> wrote in message
news:00****** *************** *******@phx.gbl ...
Can I add (append) to an xml file that already

contains a
serialized object, and be able to deserialize to either or both objects from the same file...??? How is this
done...??

thanks,

vince
.

.

Nov 15 '05 #14
Robert,

thanks for your help, it seems that my custom JobFile
type can't be serialized as a member of a strongly typed
array... tried several ways of doing this, but Serialize()
keeps telliing me that my JobFile type "can't be used in
this context".

I suspect that it's because the JobFile class inherits
from ICollection and is set up to serialize a contained
arraylist of custom objects. I think I'm trying to do too
much here, will look at your other suggested methods.

Here's the code I was using:

JobFile[] jobArray = new JobFile[2];

jobArray[0] = theJob;
jobArray[1] = theJob1;

XmlSerializer x = new XmlSerializer(j obArray.GetType ());
TextWriter writer = new StreamWriter("c :\\backup\\" +
textBox1.Text + ".xml");
x.Serialize(wri ter, jobArray);

Thanks for your help,

Vince Lusardi
-----Original Message-----
You're right -- it turns out you can't just stuff an Object[] array withcustom classes and expect it to serailize correctly. The reason is that theXmlSerialize r is kind of dumb... it needs to know what type of object isbeing stored in the array so that it can deserialize it correctly later on.Sorry for leading you astray. <g>

The easiest way around this is to use a strongly-typed array or collection.So, it should work if you replace the line "object[] jobArray = newobject[2];" with "jobFile[] jobArray = new jobFile[2];" I have some samplecode below. Alternatively, you could define a strongly- typed JobFilecollection by inheriting from CollectionBase.

Another alternative is to use the SOAP serializer or binary serializerinstead. Both are more robust than the XmlSerializer, and should be able toserialize Object[] arrays correctly. The tradeoff is that the output fromthose serializers are not as easily readable (for human eyes) than the cleanXML generated by the XmlSerailizer. Check out these articles:
http://msdn.microsoft.com/library/default.asp? url=/library/en-us/dndotnet/html/objserializ.asphttp://msdn.microsoft.com/library/default.asp? url=/library/en-us/dnadvnet/html/vbnet09252001.a sp
Hope this helps,
Robert Jacobson
using System;
using System.Xml.Seri alization;
using System.IO;
using System.Diagnost ics;

namespace ConsoleApplicat ion1
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
SerializationTe st();
}

static void SerializationTe st()
{
Object[] jobArray = new Object[2];

DummyJob job1 = new DummyJob();
job1.Name = "First Job";
jobArray[0] = job1;

DummyJob job2 = new DummyJob();
job2.Name = "Second Job";
jobArray[1] = job2;

try
{

XmlSerializer serializer = new XmlSerializer (jobArray.GetTy pe()); StreamWriter sw = new StreamWriter("T est.xml");

serializer.Seri alize(sw, jobArray);
sw.Close();
}
catch (Exception ex)
{
Debug.WriteLine (ex.ToString()) ;
}
}
}

public class DummyJob
{
public string Name;
}

}
"vince" <vl******@sdcer a.org> wrote in message
news:02******* *************** ******@phx.gbl. ..
Robert,

I would also add that theJob seriailizes fine
individually, but I can't seem to get it to do so when
it's an element of a parent container...

thanks for your time...

vince
>-----Original Message-----
>Robert,
>
>tried your suggestion of putting the 2 serializable
>objects into an Arraylist, and also an array of type
>object[], but I get runtime errors... here's the code:
>
>object[] jobArray = new object[2];
>
>jobArray[0] = theJob; //serializable custom type w/
>arraylist
>jobArray[1] = myTask; //arraylist
>XmlSerialize r x2 = new XmlSerializer(t ypeof(object [])); >TextWriter tw = new StreamWriter("c :\\backup\\" +
>textBox1.Tex t + ".xml");
>
>x2.Serialize(t w, jobArray);
>
>The exception thrown is "Job.JobFil e may not be used in >this context".... Job is the namespace, and theJob is an >object of type Job.JobFile.
>
>Did the same thing using an Arraylist to hold the two
>objects with similar results...
>
>Thanks for any further suggestions... sorry for the
>double post on newsgroups..
>
>
>>-----Original Message-----
>>Vince,
>>
>>I replied to your question in
>microsoft.publ ic.dotnet.gener al. In the
>>future, please don't repost the same question to
>multiple groups.
>>
>>There's no need to use strange workarounds to get this >done. Just define an
>>array of objects (or ArrayList, or strongly-typed
>collection), place both
>>items in the array, and serialize/deserialize the
>array. It will work fine.
>>
>>--Robert Jacobson
>>
>>
>>
>>
>>
>>"vince" <vl******@sdcer a.org> wrote in message
>>news:00****** *************** *******@phx.gbl ...
>>> Can I add (append) to an xml file that already
>contains a
>>> serialized object, and be able to deserialize to

either
>>> or both objects from the same file...??? How is this >>> done...??
>>>
>>> thanks,
>>>
>>> vince
>>
>>
>>.
>>
>.
>

.

Nov 15 '05 #15

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

Similar topics

4
3644
by: Julian Yap | last post by:
Hi all, I'm trying to get some ideas on the best way to do this. In this particular coding snippet, I was thinking of creating a dictionary of file objects and file names. These would be optional files that I could open and parse. At the end, I would easily close off the files by iterating through the dictionary. ---< CODE FOLLOWS >--- optionalfiles = {fileAreaCode: "areacode.11", fileBuild: "build.11"}
0
1378
by: Tu-Thach | last post by:
I would not recommend doing this. Instead, create a wrapper object that holds the two serializable object and mark that wrapper object as serializable as well. Then, serialize that wrapper object to have to serialize the two actual objects. Tu-Thach >-----Original Message----- >Can I add (append) to an xml file that already contains a
6
1707
by: Affan Syed | last post by:
Hi, I am getting this weird problem. I know what i am doing is strange.. i am using C++ vectors and fopen, but for some reason if i used ofstream in the similar scenario it would give me errors. So here is what i do. I create a new node and insert it in a vecotr as follows: nodeCreator = new cNode(location, skew, offset,Beaconify,nodeId,directory); gNodeVector.push_back(*nodeCreator); //now lets delete the memory we created for the node
0
1293
by: Monorom | last post by:
Hi, Is it possible to serialize objects in XML without the declaration <?xml version="1.0"?> in the the result of the serialization. I want to insert this result into antoher XML stream. Thanks Monorom
0
1177
by: Newbie H | last post by:
I can serialize several objects to the same file using binary formatter, yet only one using XML formatter I call the Serialize() method once per object, the objects are not contained in a collection Is that correct (if so, the documentation is unclear), or how can I serialize multiple objects (of same or different type) to a single xml file thank you!
3
1872
by: Sharon | last post by:
I'm using StreamWriter to write to file and at the same time I'm using the StreamReader to read from the same file. Doing that cause an exception when I'm trying to create the StreamReader when the file is already opened fro writing by the StreamWriter. How can I write and read at the same time to the same file? -- Thanks Sharon G.
4
3139
by: abrtlt | last post by:
I read in Programming PHP (O'Reilly) that flock() "cannot prevent two PHP scripts running in the same web server process from accessing a file at the same time". In my case a single PHP script appends text strings to an existing text file. Several clients may trigger the same script on the same web page and thus more than one PHP instance might try to open and append text to the same file at the same time. I would assume that using...
8
10537
by: Raghu | last post by:
Is it possible to write a new file and after writing few bytes, is it possible to read from it from another file stream while write continues? Is there another steam for this type of operation? Thanks. Raghu/..
0
1222
by: soccerdad | last post by:
I'm trying to make sure that I'm using the correct .NET 2.0 mechanism to serialize objects to XML files. I've used XSD.EXE to generate classes from a 3rd party .xsd file. I can populate those objects, etc. At present, I'm using the following code to create a .xml file from the root element of those objects: FileStream fs = new FileStream(targetFileName, FileMode.CreateNew); try {
2
5441
by: DJ Dharme | last post by:
Hi all, I am writing a multi-threaded application in c++ running on solaris. I have a file which is updated by a single thread by appending data into the file and at same time the other threads are reading the content written into the file. Can anybody tell me is there a performance or any other gain (except for the multex locking) by using different file descriptors in each thread for the same file rather than using a single FD with a...
0
9456
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
9843
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9713
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7248
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5142
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3805
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3358
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2666
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.