Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 932
  • Last Modified:

How to do serialization and deserialization in c#?

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
tryokane
Asked:
tryokane
  • 10
  • 8
  • 2
  • +2
1 Solution
 
tchamtiehCommented:
Take a look at this example:

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

Good Luck
0
 
tryokaneAuthor Commented:
This is ok but i want to know how to read xml from a stream and serialize it by using the above method.
0
 
tchamtiehCommented:
0
NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

 
tryokaneAuthor Commented:
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
 
margajet24Commented:
0
 
SameerJagdaleCommented:
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
 
MarkMyburghCommented:
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
 
tryokaneAuthor Commented:
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
 
MarkMyburghCommented:
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
 
MarkMyburghCommented:

found this might help you out
http://forums.asp.net/t/1323181.aspx 
0
 
tryokaneAuthor Commented:
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
 
MarkMyburghCommented:
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
 
tryokaneAuthor Commented:
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
 
MarkMyburghCommented:
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
 
tryokaneAuthor Commented:
"There is an error in XML document (312, 6)".This is the error which i get now.
0
 
MarkMyburghCommented:
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
 
tryokaneAuthor Commented:

<?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
 
tryokaneAuthor Commented:
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
 
MarkMyburghCommented:
I'm stumped on this one.  I'm able to save an xml without any input values.
Is there any relationship on OrderItemPayor?  

0
 
tryokaneAuthor Commented:
No the output should be like this when i need to send.The Billinfo tag should be empty.
0
 
MarkMyburghCommented:
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
 
tryokaneAuthor Commented:
Ok i am able to figure out.Thanks a lot for the help.
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 10
  • 8
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now