XML De-serialization giving null values - c#

i am having an XML string like
<?xml version="1.0"?>
<FullServiceAddressCorrectionDelivery xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<AuthenticationInfo xmlns="http://www.usps.com/postalone/services/UserAuthenticationSchema">
<UserId xmlns="">FAPushService</UserId>
<UserPassword xmlns="">Password4Now</UserPassword>
</AuthenticationInfo>
</FullServiceAddressCorrectionDelivery>
In Order to map the nodes with Class, i am having the class structure like
[Serializable]
public class FullServiceAddressCorrectionDelivery
{
[XmlElement("AuthenticationInfo")]
public AuthenticationInfo AuthenticationInfo
{
get;
set;
}
}
[Serializable]
public class AuthenticationInfo
{
[XmlElement("UserId")]
public string UserId
{
get;
set;
}
[XmlElement("UserPassword")]
public string UserPassword
{
get;
set;
}
}
For De-serialization , i used xmlserializer to De-serialize the object
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(xmlString);
MemoryStream stream = new MemoryStream(byteArray);
XmlSerializer xs = new XmlSerializer(typeof(FullServiceAddressCorrectionDelivery));
var result = (FullServiceAddressCorrectionDelivery)xs.Deserialize(stream);
but the value FullServiceAddressCorrectionDelivery object is always null..
please help me what i am doing wrong here....

Add namesapce on the XmlElement attribute as described here
[Serializable]
public class FullServiceAddressCorrectionDelivery
{
[XmlElement("AuthenticationInfo",
Namespace =
"http://www.usps.com/postalone/services/UserAuthenticationSchema")]
public AuthenticationInfo AuthenticationInfo
{
get;
set;
}
}
[Serializable]
public class AuthenticationInfo
{
[XmlElement("UserId", Namespace="")]
public string UserId
{
get;
set;
}
[XmlElement("UserPassword", Namespace = "")]
public string UserPassword
{
get;
set;
}
}

Related

Deserialize an XML using XMLSerializer

I'm trying to deserialize an XML file with XmlSerializer. However i am getting this exception: There is an error in XML document (1, 41).InnerException Message "ReplicationStatus xmlns='DistributionServices' was not expected."
The XML file looks like this:
<?xml version="1.0" encoding="UTF-8" ?>
<ts:Status xmlns:ts="DistributionServices">
<Server>DUMMY</Server>
<Object>DUMMY</Object>
<Port>123</Port>
<Code>DUMMY</Code>
<Key>b0ed5e56</Key>
</ts:Status>
The code that I have used is as follows:
MessageData data = new MessageData();
XmlSerializer xmlSerializer = new XmlSerializer(data.GetType());
data = (MessageData)xmlSerializer.Deserialize(new StringReader(msgData));
Here, msgData is the string containing the xml shown above.
MessageData class looks like this:
[Serializable,XmlType("Status")]
public class MessageData
{
[XmlElement("Server")]
public string Server { get; set; }
[XmlElement("Object")]
public string Object { get; set; }
[XmlElement("Port")]
public string Port { get; set; }
[XmlElement("Code")]
public string Code { get; set; }
[XmlElement("Key")]
public string Key { get; set; }
}
Please let me know what I am doing wrong.
You have to declare the namespace in your class and set it to empty on your properties. Change your class model to this and it should work fine.
[Serializable, XmlRoot("Status", Namespace = "DistributionServices")]
public class MessageData
{
[XmlElement(Namespace = "")]
public string Server { get; set; }
[XmlElement(Namespace = "")]
public string Object { get; set; }
[XmlElement(Namespace = "")]
public string Port { get; set; }
[XmlElement(Namespace = "")]
public string Code { get; set; }
[XmlElement(Namespace = "")]
public string Key { get; set; }
}
BTW: you don't have to name XmlElement's explicit if they have the same name as the property.

How to Serialize Nested Classes and Collections into XML?

First, i tried on the internet different ways, but i didn't got what i want. i have viewmodel class with the following properties;
public class UserEntitySubmissionsReportViewModel
{
public UserEntitySubmissionsReportViewModel()
{
Submissions = new FinalUserEntitiesAssignmentViewModel();
}
public int Id { get; set; }
public int Status { get; set; }
public DateTime SubmissionDate { get; set; }
public int UserEntityAssignmentId { get; set; }
public FinalUserEntitiesAssignmentViewModel Submissions { get; set; }
}
and the nested class FinalUserEntitiesAssignmentViewModel whcih is;
[Serializable]
public class FinalUserEntitiesAssignmentViewModel
{
public FinalUserEntitiesAssignmentViewModel()
{
ProjectInformation = new ProjectInformationViewModel();
MilestoneInformation = new MilestoneInformationViewModel();
ActivityListInformation = new ActivityListInformationViewModel();
ActivityInformation = new ActivityInformationViewModel();
SubActivityInformation = new List<SubActivityInformationViewModel>();
}
[XmlElement(ElementName = "ProjectInformation")]
public ProjectInformationViewModel ProjectInformation { get; set; }
[XmlElement(ElementName = "MilestoneInformation")]
public MilestoneInformationViewModel MilestoneInformation { get; set; }
[XmlElement(ElementName = "ActivityListInformation")]
public ActivityListInformationViewModel ActivityListInformation { get; set; }
[XmlElement(ElementName = "ActivityInformation")]
public ActivityInformationViewModel ActivityInformation { get; set; }
[XmlElement(ElementName = "SubActivityInformation")]
public List<SubActivityInformationViewModel> SubActivityInformation { get; set; }
}
[Serializable]
public class ProjectInformationViewModel
{
[XmlElement(ElementName = "Id")]
public int Id { get; set; }
[XmlElement(ElementName = "Name")]
public string Name { get; set; }
public string Description { get; set; }
}
When i serialize this, i only get the 1 property i.e Id for nested class.
var obj = new UserEntitySubmissionsReportViewModel();
var writer = new System.Xml.Serialization.XmlSerializer(typeof(UserEntitySubmissionsReportViewModel));
System.IO.StreamWriter file = new System.IO.StreamWriter(Server.MapPath("~/App_Data/UserEntitySubmissionsReportViewModel.xml"));
writer.Serialize(file, obj);
file.Close();
The result i get is;
<?xml version="1.0" encoding="utf-8"?>
<UserEntitySubmissionsReportViewModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Id>0</Id>
<Status>0</Status>
<SubmissionDate>0001-01-01T00:00:00</SubmissionDate>
<UserEntityAssignmentId>0</UserEntityAssignmentId>
<Submissions>
<ProjectInformation>
<Id>0</Id>
</ProjectInformation>
<MilestoneInformation>
<Id>0</Id>
</MilestoneInformation>
<ActivityListInformation>
<Id>0</Id>
</ActivityListInformation>
<ActivityInformation>
<Id>0</Id>
<Attributes />
<Tools />
</ActivityInformation>
</Submissions>
</UserEntitySubmissionsReportViewModel>
As you can see, i am not able to serialize other properties. Similarly i have nest collection too. How can i serialize nested properties using C# ?
I think that when serializing XML that you need to define a default constructor for your classes. Try adding a construction for your ProjectInformationViewModel class.
public class ProjectInformationViewModel
{
// Default Constructor
public ProjectInformationViewModel()
{
}
}

remove xmlns:i="http://www.w3.org/2001/XMLSchema-instance" when using DataContractSerializer

how can I remove the xmlns:i="http://www.w3.org/2001/XMLSchema-instance" when using DataContractSerializer.
this is what I'm getting:
<ProfileModel xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Email>wolverine#wolverine.com</Email>
<FirstName>wolverine</FirstName>
<ID>ty1002225</ID>
<LastName>wolverine3</LastName>
<PhoneNumber>66332214477</PhoneNumber>
<SourceSystem>TY</SourceSystem>
</ProfileModel>
I want to get something like this:
<ProfileModel>
<Email>wolverine#wolverine.com</Email>
<FirstName>wolverine</FirstName>
<ID>ty1002225</ID>
<LastName>wolverine3</LastName>
<PhoneNumber>66332214477</PhoneNumber>
<SourceSystem>TY</SourceSystem>
</ProfileModel>
this is my model:
[DataContract(Namespace = "")]
public class CRMProfileModel
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public string Email { get; set; }
[DataMember]
public string PhoneNumber { get; set; }
[DataMember]
public string SourceSystem { get; set; }
[DataMember]
public string ID { get; set; }
}
I'm trying to avoid to use string replace to remove it.
how can I remove the xmlns:i="http://www.w3.org/2001/XMLSchema-instance" when using DataContractSerializer.
hii Romeo... i also tried for couple of hours to remove xmlns:i="http://www.w3.org/2001/XMLSchema-instance".
Finally i found my best,hope it will helpful
public IHttpActionResult Post([FromBody]MessageResponse value)
{
var messageresponse =new CRMProfileModel(){.....};
DataContractSerializer doc = new DataContractSerializer(messageresponse.GetType());
MemoryStream ms = new MemoryStream();
dcs.WriteObject(ms, messageresponse);
var i = Encoding.UTF8.GetString(ms.ToArray());
var r = i.Replace("xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"","");
var ss = new XmlDocument();
ss.LoadXml(r);
return Content(HttpStatusCode.OK, ss.DocumentElement, Configuration.Formatters.XmlFormatter);
}

XML deserialize derived class

The problem is XmlType("Erand") name is same as my class Erand, if I changed the class name to like Eranda it worked, is there any other way to say .net what to do?
I have an class
public class Erand
{
public long ID { get; set; }
public string AsjaNumber { get; set; }
}
and
[XmlType("Erand")]
public class ErandTsiv : Erand
{
[XmlElement("ID_KIS")]
public long idKis { get; set; }
[XmlElement("ID_ET")]
public long idEt { get; set; }
}
I want to deserialize ErandTsiv
from xml like
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfErand xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Erand>
<ID>573838383</ID>
<ID_KIS>573838383</ID_KIS>
<ID_ET></ID_ET>
<AsjaNumber>2-08-88785</AsjaNumber>
</Erand>
</ArrayOfErand>
like
var stream = new StringReader(erandid);
var serializer = new XmlSerializer(new List<ErandTsiv>().GetType());
var erandTsivs = (IList<ErandTsiv>)serializer.Deserialize(stream);`
but get an error
{"There was an error reflecting type 'System.Collections.Generic.List`1[Aet.test.unit.application.utility.TsivTapsustaTest.ErandTsiv]'."}
To deserialize this exact XML you should rely on a custom List definition for your List<ErandTsiv>, leaving out the XmlType on ErandTsiv
Your class definitions would then be :
public class Erand
{
public long ID { get; set; }
public string AsjaNumber { get; set; }
}
public class ErandTsiv : Erand
{
[XmlElement("ID_KIS")]
public long idKis { get; set; }
[XmlElement("ID_ET")]
public long idEt { get; set; }
}
[XmlRoot("ArrayOfErand")]
public class ErandTsivList
{
public ErandTsivList()
{
Erands = new List<ErandTsiv>();
}
[XmlElement("Erand")]
public List<ErandTsiv> Erands { get; set; }
}
And the deserialization would be :
var stream = new StringReader(x);
var serializer = new XmlSerializer(typeof(ErandTsivList));
var erandTsivs = (ErandTsivList)serializer.Deserialize(stream);
// your List<ErandTsiv> would then be in erandTsivs.Erands

I need to know how to deserialize a specific XML into objects defined in a custom class in C#

Given the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<userAttributeList>
<attribute>
<userId>12345678</userId>
<attId>1234</attId>
<attName>Group</attName>
<attTypeId>8</attTypeId>
<attTypeName>User Group</attTypeName>
<attData>Member</attData>
</attribute>
<attribute>
<userId>12345678</userId>
<attId>1235</attId>
<attName>Contact Name</attName>
<attTypeId>16</attTypeId>
<attTypeName>Contact Center Greeting</attTypeName>
<attData>John Smith</attData>
</attribute>
...
</userAttributeList>
I want to deserialize it into the following classes:
[Serializable]
[XmlTypeAttribute(AnonymousType = true)]
public class UserAttributeList
{
[XmlArray(ElementName = "userAttributeList")]
[XmlArrayItem(ElementName = "attribute")]
public List<UserAttribute> attributes { get; set; }
public UserAttributeList()
{
attributes = new List<UserAttribute>();
}
}
[Serializable]
public class UserAttribute
{
public String userId { get; set; }
public String attId { get; set; }
public String attName { get; set; }
public String attTypeId { get; set; }
public String attTypeName { get; set; }
public String attData { get; set; }
}
Using the code below, where GetResponseStream() returns the XML object listed above:
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "userAttributeList";
xRoot.IsNullable = true;
XmlSerializer serializer = new XmlSerializer(typeof(UserAttributeList), xRoot);
try
{
return (UserAttributeList)serializer.Deserialize(request.GetResponse().GetResponseStream());
}
catch (Exception exc)
{
return null;
}
My code compiles with no errors, but the UserAttributeList that is returned shows no child "attribute" items. No errors are thrown
I would sooner do something like:
public class userAttributeList
{
[XmlElement]
public List<UserAttribute> attribute { get; set; }
public UserAttributeList()
{
attribute = new List<UserAttribute>();
}
}
public class UserAttribute
{
public int userId { get; set; }
public int attId { get; set; }
public string attName { get; set; }
public int attTypeId { get; set; }
public string attTypeName { get; set; }
public string attData { get; set; }
}
Personally I'd use LinqToXsd. Take the existing xml, generate an xsd from it then use LinqToXsd to load that xml into a LinqToXsd object. Then you can do things like:
xml.company.com.reports.report.Load(xmlFileContents);
to build a POCO.

Categories

Resources