Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How to do serialization and deserialization in c#?

Posted on 2008-10-13
22
Medium Priority
?
922 Views
Last Modified: 2013-12-17
I am new to this concept.I have to read xml from an xml stream  and serialize and later after performing some calculations on the xml data i have to deserialize ? Can anyone tell me how to do?
0
Comment
Question by:tryokane
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 8
  • 2
  • +2
22 Comments
 
LVL 6

Expert Comment

by:tchamtieh
ID: 22708428
Take a look at this example:

http://geekswithblogs.net/timh/archive/2006/02/09/68857.aspx

Good Luck
0
 
LVL 2

Author Comment

by:tryokane
ID: 22708440
This is ok but i want to know how to read xml from a stream and serialize it by using the above method.
0
 
LVL 6

Expert Comment

by:tchamtieh
ID: 22708456
0
Stressed Out?

Watch some penguins on the livecam!

 
LVL 2

Author Comment

by:tryokane
ID: 22708472
I think u didnt understand my question.I have to read xml from a stream and then serialize it.I already prepared a class clsPerson with some properties like firstname,lastname etc..How to do this?
0
 
LVL 10

Expert Comment

by:margajet24
ID: 22708492
0
 
LVL 13

Expert Comment

by:SameerJagdale
ID: 22708716
hope this helps:
clsPerson person = new clsPerson();
person.FirstName = "Sameer";
person.LastName = "Jagdale";
 
Stream stream = new FileStream("person.xml", FileMode.Create, FileAccess.ReadWrite);
 
IFormatter myformatter = new SoapFormatter();
 
myformatter.Serialize(stream, person);

Open in new window

0
 
LVL 1

Expert Comment

by:MarkMyburgh
ID: 22709715
not sure if i'm understanding your.
you have a xml document that you want to do what with?  
I take it you want to send the new xml back up the stack right.  What transport method do you want to use?  Below is just a simple example of how to take any object, this case being an xml document, and then converts it into a string or you can change the method to return a byte[].
hope i understood what your asking for.
later

 static private string UTF8ByteArrayToString(Byte[] characters)
            {
 
                UTF8Encoding encoding = new UTF8Encoding();
                String constructedString = encoding.GetString(characters);
                return (constructedString);
            }
 
            internal static string example(object doc)
            {
                var memoryStream = new MemoryStream();
 
                try
                {
                    XmlSerializer serializer = new XmlSerializer(doc.GetType());
                    XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
                    serializer.Serialize(xmlTextWriter, doc);
                    memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
                    return UTF8ByteArrayToString(memoryStream.ToArray());
                }
                catch (Exception e)
                {
                    return "";
                }
                finally
                {
                    memoryStream.Flush();
                    memoryStream.Close();
                    memoryStream.Dispose();
                }
            }

Open in new window

0
 
LVL 2

Author Comment

by:tryokane
ID: 22737626
Ok,Now i get a problem"There was an error reflecting type" when i tried to execute.How to solve this one.Can anyone tell me?
0
 
LVL 1

Expert Comment

by:MarkMyburgh
ID: 22738370
can i have a look at the code your using?
could be that the compiler cannot convert say a string to an int if the string.value is not a valid int.
just a stab in the dark tho.
0
 
LVL 1

Expert Comment

by:MarkMyburgh
ID: 22738399

found this might help you out
http://forums.asp.net/t/1323181.aspx 
0
 
LVL 2

Author Comment

by:tryokane
ID: 22742118
Ok,i was able to solve it but now i got another new problem like"There was an error in the xml message".I tried to find out and came to know that it was because when a particular xml tag is empty it was leading to this error.Can anyone help me out?The code snippet  is below.I am getting an error with the OIDuration element because it is not able to deserialize when the element is empty(there is no data).

  [XmlElement(ElementName = "OIDuration")]
    public int Duration
    {
      get { return m_Duration; }
      set { m_Duration = value; }
    }
      [XmlElement(ElementName = "OIOrderingLocation", IsNullable = true)]
    public string OrderingLocation
    {
      get { return m_OrderingLocation; }
      set { m_OrderingLocation = value; }
    }

Open in new window

0
 
LVL 1

Accepted Solution

by:
MarkMyburgh earned 375 total points
ID: 22744833
how are you deserilising/
i had some issues with this as well and found a better method to implement .

 public static object XmlDeserialize(XmlDocument doc, Type t)
        {
            MemoryStream stream = new MemoryStream();
 
            doc.Save(stream);
 
            stream.Position = 0;
 
            return new XmlSerializer(t).Deserialize(stream);
        }
        public static XmlDocument XmlSerialize(Customer customer, Type t)
        {
            XmlDocument doc = new XmlDocument();
            MemoryStream stream = new MemoryStream();
 
            new XmlSerializer(t).Serialize(stream, customer);
 
            stream.Position = 0;
 
            doc.Load(stream);
 
            return doc;
        }

Open in new window

0
 
LVL 2

Author Comment

by:tryokane
ID: 22755353
The below method i followed.Whenever a particular tag element is empty it is giving error.
TextReader reader = new StreamReader(fDialog.FileName.ToString());
                string xmlString = reader.ReadToEnd();
 
 
                 XmlDocument doc = new XmlDocument();
                TextReader reader = new StreamReader(fDialog.FileName.ToString());
                string xmlString = reader.ReadToEnd();doc.LoadXml(xmlString);
                XmlNodeReader xmlreader = new XmlNodeReader(doc.DocumentElement);
                XmlSerializer ser = new XmlSerializer(typeof(PatientBillRequest));
                PatientBillRequest objPatientBillRequest = (PatientBillRequest)ser.Deserialize(xmlreader);

Open in new window

0
 
LVL 1

Expert Comment

by:MarkMyburgh
ID: 22755673
try adding this code after line 9 of your code snippet.
remove line 10;
            MemoryStream stream = new MemoryStream();
            doc.Save(stream);
            stream.Position = 0;
            (PatientBillRequest) XmlSerializer(t).Deserialize(stream);
 
0
 
LVL 2

Author Comment

by:tryokane
ID: 22755701
"There is an error in XML document (312, 6)".This is the error which i get now.
0
 
LVL 1

Expert Comment

by:MarkMyburgh
ID: 22755723
hmmm can you post the xml document your trying to serialise?
got a feeling it might just be a error in the formating of your xml.
0
 
LVL 2

Author Comment

by:tryokane
ID: 22755736

<?xml version="1.0" encoding="utf-8"?>
<PATIENTBILL xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	
    <HEADER>
    <BillID>G78889</BillID>
    <BillSubmitDate>2008-07-14</BillSubmitDate>
    <BillSubmitTime>02:55:36.82</BillSubmitTime>
    </HEADER>
		
	<PATIENT>
    <PatientID>G879030</PatientID>
    <PatientNumber>900090</PatientNumber>
    <PatientFirstName>Mary</PatientFirstName>
    <PatientFamilyName>Lee</PatientFamilyName>
    <PassportNumber>G889990</PassportNumber>
    <MRNNumber>MR0090</MRNNumber>
    </PATIENT>
	
	<PAYPLN>
    <PayorPlanID>IP10</PayorPlanID>
    <Payor>MediSave</Payor>
    <Plan>Medi120</Plan>
    <PayorRank>3</PayorRank>
    <AccountNumber>AC0900</AccountNumber>
	<BillAmount>12000</BillAmount>
    <BillPercent>10</BillPercent>
    </PAYPLN>
	
	
	<EPISODE>
    <EpisodeID>EP001</EpisodeID>
    <EpisodeNumber>78821</EpisodeNumber>
    <EpisodeType>I</EpisodeType>
    <EpisodeSubType>Inpatient</EpisodeSubType>
    <EpisodeDate>2008-07-07</EpisodeDate>
    <EpisodeTime>12:58:36.40</EpisodeTime>
	<AdmissionLocation>M34</AdmissionLocation>
	<AdmissionCareProvider>89782R</AdmissionCareProvider>
	<AdmissionBedCode>B01</AdmissionBedCode>
    <AdmissionWard>WD001</AdmissionWard>
    <AdmissionBedTypeCode>BD001</AdmissionBedTypeCode>
    <BillingGroupCode>001</BillingGroupCode>
    <BillingSubGroupCode>101</BillingSubGroupCode>
    <AdmissionRoomTypeCode>ADR20</AdmissionRoomTypeCode>
    <PreferredAccomodation>4BED</PreferredAccomodation>
    <DischargeDate>2008-07-14</DischargeDate>
    <DischargeTime>01:23:32.01</DischargeTime>
    <Diagnosis></Diagnosis>
    <Diagnosis></Diagnosis>
    <Diagnosis></Diagnosis>
    <DiagnosisType></DiagnosisType>
    </EPISODE>
	
		
	<IPMOVE>
    <IPMovementID>86894</IPMovementID>
    <DestinationLocation>QuantaTech Holdings Inc.</DestinationLocation>
    <TransferStartDate>2008-07-08</TransferStartDate>
    <TrasnsferStartTime>10:04:12.75</TrasnsferStartTime>
    <TrasnferToBed>T76</TrasnferToBed>
    <TransferToWard>R1478</TransferToWard>
    <TransferToBedType>E5</TransferToBedType>
    <TransferToRoomType>D8</TransferToRoomType>
    </IPMOVE>
	
	
	
	<IPTHAN>
    <TheatreID>1</TheatreID>
    <ChargeCode>Y61</ChargeCode>
    <OperationStatus>CANCELLED</OperationStatus>
    <AnaestheticMethod>X2996</AnaestheticMethod>
    <AnaestheticStatus>DONE</AnaestheticStatus>
    <AnaestheticAgent>T5282</AnaestheticAgent>
	<Anaest.StartDate>2008-07-10</Anaest.StartDate>
    <Anaest.StartTime>22:48:08.06</Anaest.StartTime>
    <Anaest.EndDate>2008-07-10</Anaest.EndDate>
    <Anaest.EndTime>23:24:37.11</Anaest.EndTime>
    </IPTHAN>
		
    <IPTHTR>
    <TheatreID>1</TheatreID>
    <Procedure>H8193</Procedure>
    <TableCode>Q30</TableCode>
    <Priority>A57</Priority>
	<TheatreInDate>2008-07-10</TheatreInDate>
    <TheatreInTime>22:48:08.06</TheatreInTime>
    <TheatreOutDate>2008-07-10</TheatreOutDate>
    <TheatreOutTime>23:24:37.11</TheatreOutTime>
    <OperationStatus>CANCELLED</OperationStatus>
	<PACUStartDate>2008-07-10</PACUStartDate>
    <PACUStartTime>22:48:08.06</PACUStartTime>
    <PACUReadyToLeaveDate>2008-07-10</PACUReadyToLeaveDate>
    <PACUReadyToLeaveTime>23:24:37.11</PACUReadyToLeaveTime>
    </IPTHTR>
			
	<ORDITEM>
    <OrderItemRowID>111000</OrderItemRowID>
    <OrderItemCode>AD76778</OrderItemCode>
    <BillingGroupCode>PHARMACY</BillingGroupCode>
    <BillingSubGroupCode>PHARMACY</BillingSubGroupCode>
    <OrderCategory>GENERAL PHARMACY</OrderCategory>
    <OrderSubCategory>CARBOHYDRATES</OrderSubCategory>
    <OrderSetCode></OrderSetCode>
	<StartDate>2008-07-07</StartDate>
    <StartTime>21:21:42.81</StartTime>
    <EndDate>2008-07-08</EndDate>
    <EndTime>06:30:03.83</EndTime>
    <Quantity>1</Quantity>
    <OIDuration>12</OIDuration>
    <OIOrderingLocation>O1409</OIOrderingLocation>
    <GeneratedOIIndicator>H2233</GeneratedOIIndicator>
	<BillingStatus>I900</BillingStatus>
    <OIReceivingLocation>O1409</OIReceivingLocation>
    <ListPrice>100</ListPrice>
	<ItemPrice>150</ItemPrice>
	<ManualOverridePrice>1133</ManualOverridePrice>
    <DiscountedAmount>0</DiscountedAmount>
    <PharmacyRafflesClassificationCode>X788</PharmacyRafflesClassificationCode>
	<ClinicLocation>J989</ClinicLocation>
    <ApptID>A7893</ApptID>
	<ApptDate>2008-07-07</ApptDate>
    <ApptTime>11:15:39.26</ApptTime>
   	<ApptStatus>G983</ApptStatus>
	<ArrivalDate>2008-07-07</ArrivalDate>
	<ArrivalTime>03:54:54.35</ArrivalTime>
    <DepartureDate>2008-07-15</DepartureDate>
    <DepartureTime>03:54:54.35</DepartureTime>
    <CareProvider>Surgeon</CareProvider>
    <CareProviderType>Surgeon</CareProviderType>
    <ServiceRendered></ServiceRendered>
    <ServiceTaxCode>X9990</ServiceTaxCode>
    <OIUrgency>I90</OIUrgency>
    </ORDITEM>
	
	<ORDITEM>
    <OrderItemRowID>111001</OrderItemRowID>
    <OrderItemCode>AD78649</OrderItemCode>
    <BillingGroupCode>CONSULTATION</BillingGroupCode>
    <BillingSubGroupCode>IP CONSULTATION</BillingSubGroupCode>
    <OrderCategory>APPOINTMENT</OrderCategory>
    <OrderSubCategory>CONSULTATION</OrderSubCategory>
    <OrderSetCode></OrderSetCode>
    <StartDate>2008-07-07</StartDate>
    <StartTime>21:21:42.81</StartTime>
    <EndDate>2008-07-08</EndDate>
    <EndTime>06:30:03.83</EndTime>
    <Quantity>1</Quantity>
    <OIDuration>12</OIDuration>
    <OIOrderingLocation>O1410</OIOrderingLocation>
    <GeneratedOIIndicator>433</GeneratedOIIndicator>
	<BillingStatus>I900</BillingStatus>
	<OIReceivingLocation>O1410</OIReceivingLocation>
    <ListPrice>1000</ListPrice>
    <ItemPrice>1500</ItemPrice>
	<ManualOverridePrice>112</ManualOverridePrice>
    <DiscountedAmount>0</DiscountedAmount>
    <PharmacyRafflesClassificationCode></PharmacyRafflesClassificationCode>
	<ClinicLocation>J989</ClinicLocation>
    <ApptID>A7897</ApptID>
	<ApptDate>2008-07-07</ApptDate>
    <ApptTime>11:15:39.26</ApptTime>
   	<ApptStatus>G983</ApptStatus>
	<ArrivalDate>2008-07-07</ArrivalDate>
	<ArrivalTime>03:54:54.35</ArrivalTime>
    <DepartureDate>2008-07-15</DepartureDate>
    <DepartureTime>03:54:54.35</DepartureTime>
	<CareProvider>Surgeon</CareProvider>
    <CareProviderType>Surgeon</CareProviderType>
    <ServiceRendered></ServiceRendered>
    <ServiceTaxCode>X9990</ServiceTaxCode>
    <OIUrgency>I90</OIUrgency>
    </ORDITEM>
	
	
	
	<ORDITEM>
    <OrderItemRowID>111004</OrderItemRowID>
    <OrderItemCode>AD423424</OrderItemCode>
    <BillingGroupCode>PROCEDURES</BillingGroupCode>
    <BillingSubGroupCode>MEDICAL PROCEDURE</BillingSubGroupCode>
    <OrderCategory>PROCEDURES</OrderCategory>
    <OrderSubCategory>MEDICAL PROCEDURE</OrderSubCategory>
    <OrderSetCode></OrderSetCode>
    <StartDate>2008-07-07</StartDate>
    <StartTime>21:21:42.81</StartTime>
    <EndDate>2008-07-08</EndDate>
    <EndTime>06:30:03.83</EndTime>
    <Quantity>3</Quantity>
		<OIDuration>12</OIDuration>
    <OIOrderingLocation>O1410</OIOrderingLocation>
    <GeneratedOIIndicator>433</GeneratedOIIndicator>
	<BillingStatus></BillingStatus>
    <OIReceivingLocation>O1410</OIReceivingLocation>
    <ListPrice>300</ListPrice>
	<ItemPrice>500</ItemPrice>
	<ManualOverridePrice></ManualOverridePrice>
    <DiscountedAmount>0</DiscountedAmount>
    <PharmacyRafflesClassificationCode></PharmacyRafflesClassificationCode>
    <ApptID>A7800</ApptID>
	<ApptDate>2008-07-07</ApptDate>
	<ApptTime>11:15:39.26</ApptTime>
   	<ApptStatus>G983</ApptStatus>
	<ArrivalDate>2008-07-07</ArrivalDate>
	<ArrivalTime>03:54:54.35</ArrivalTime>
    <DepartureDate>2008-07-15</DepartureDate>
    <DepartureTime>03:54:54.35</DepartureTime>
    <CareProvider>Surgeon</CareProvider>
    <CareProviderType>Surgeon</CareProviderType>
    <ServiceRendered></ServiceRendered>
    <ServiceTaxCode>X9990</ServiceTaxCode>
    <OIUrgency>I90</OIUrgency>
    </ORDITEM>
	
	<BILLINFO>
    <BillItemRowId></BillItemRowId>
    <OrderItemCode></OrderItemCode>
    <StartDate></StartDate>
    <StartTime></StartTime>
    <EndDate></EndDate>
    <EndTime></EndTime>
    <Quantity></Quantity>
    <OIDuration></OIDuration>
    <OIOrderingLocation></OIOrderingLocation>
    <GeneratedOIIndicator></GeneratedOIIndicator>
    <ItemUnitPrice>0</ItemUnitPrice>
    <ManualPriceOverride>0</ManualPriceOverride>
    <OrderItemPayor></OrderItemPayor>
    <OrderItemPayor></OrderItemPayor>
    <OrderItemPayor></OrderItemPayor>
    <OrderItemPlan></OrderItemPlan>
    <OrderItemTotal>0</OrderItemTotal>
    <OrderItemGST>0</OrderItemGST>
    <ContractAdjustment>534534</ContractAdjustment>
    <OIErrorMessage></OIErrorMessage>
    <BillingErrorMessage></BillingErrorMessage>
    <BillingDebugMessage></BillingDebugMessage>
    </BILLINFO>
	
</PATIENTBILL>

Open in new window

0
 
LVL 2

Author Comment

by:tryokane
ID: 22755761
I observed the xml and found out that when the element <OrderItemPayor> is empty in the BillIInfo Segment it was leading to this error.Is that so.If so how to prevent this error?
0
 
LVL 1

Expert Comment

by:MarkMyburgh
ID: 22756045
I'm stumped on this one.  I'm able to save an xml without any input values.
Is there any relationship on OrderItemPayor?  

0
 
LVL 2

Author Comment

by:tryokane
ID: 22756060
No the output should be like this when i need to send.The Billinfo tag should be empty.
0
 
LVL 1

Expert Comment

by:MarkMyburgh
ID: 22756082
two things i have pickup but might not make a difference..
not sure if this could have an impact but why do have 3 OrderItemPayor?
Just wonding if the compiler is getting confussed when trying to deserialize back into an object.
also try changing your header on the xml you have the xmins:xsl try adding the xsd tag as well
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
0
 
LVL 2

Author Closing Comment

by:tryokane
ID: 31505774
Ok i am able to figure out.Thanks a lot for the help.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It seems a simple enough task, yet I see repeated questions asking how to do it: how to pass data between two forms. In this article, I will show you the different mechanisms available for you to do just that. This article is directed towards the .N…
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question