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()
{
}
}
Related
There is a problem, that the object fields are initialized as null.
I've checked a couple of examples, I've set the field annotations, but seems like I did something wrong.
So here is my xml file:
<?xml version="1.0" encoding="UTF-8"?>
<getInvoiceReply>
<invoiceID value="944659502"/>
<invFastener>
<fastenerID value=""/>
<fastenerName value=""/>
<fastenerCount value=""/>
<fastenerProperty>
<propID value=""/>
<propName value=""/>
<propValue value=""/>
</fastenerProperty>
</invFastener>
</getInvoiceReply>
I've created the class hierarcy.
Root class InvoiceReply :
[XmlRoot("getInvoiceReply")]
public class InvoiceReply
{
[XmlAttribute("invoiceID")]
public string InvoiceId { get; set; }
[XmlArray("invFastener")]
public List<InvFastener> InvFastener { get; set; }
}
class InvFastener :
public class InvFastener
{
[XmlAttribute("fastenerID")]
public string FastenerID { get; set; }
[XmlAttribute("fastenerName")]
public string FastenerName { get; set; }
[XmlAttribute("fastenerCount")]
public string FastenerCount { get; set; }
[XmlArray("fastenerProperty")]
public List<FastenerProperty> FastenerProperty { get; set; }
}
class FastenerProperty:
public class FastenerProperty
{
[XmlAttribute("propID")]
public string PropId { get; set; }
[XmlAttribute("propName")]
public string PropName { get; set; }
[XmlAttribute("propValue")]
public string PropValue { get; set; }
}
Test code:
InvoiceReply i = null;
var serializer = new XmlSerializer(typeof(InvoiceReply));
using (var reader = XmlReader.Create("C:\\filePathHere\\test.xml"))
{
i = (InvoiceReply)serializer.Deserialize(reader);
}
Could anyone please suggest why is this happens?
You have a few issues with your objects. You are trying to get attributes in place of elements and your arrays are not arrays, they are merely complex elements. Below is a working example that matches your xml schema
class Program
{
static void Main(string[] args)
{
string xml = #"<?xml version=""1.0"" encoding=""UTF-8""?>
<getInvoiceReply>
<invoiceID value=""944659502""/>
<invFastener>
<fastenerID value=""""/>
<fastenerName value=""""/>
<fastenerCount value=""""/>
<fastenerProperty>
<propID value=""""/>
<propName value=""""/>
<propValue value=""""/>
</fastenerProperty>
</invFastener>
</getInvoiceReply>";
var serializer = new XmlSerializer(typeof(InvoiceReply));
var i = (InvoiceReply)serializer.Deserialize(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xml)));
Console.ReadKey();
}
}
//Generic class for getting value attribute
public class ValueElement
{
[XmlAttribute("value")]
public string Value { get; set; }
}
[XmlRoot("getInvoiceReply")]
public class InvoiceReply
{
[XmlElement("invoiceID")]
public ValueElement InvoiceId { get; set; } //This is a value element
[XmlElement("invFastener")]
public List<InvFastener> InvFastener { get; set; } //This is an element, not an array
}
public class InvFastener
{
[XmlElement("fastenerID")]
public ValueElement FastenerID { get; set; }//This is a value element
[XmlElement("fastenerName")]
public ValueElement FastenerName { get; set; }//This is a value element
[XmlElement("fastenerCount")]
public ValueElement FastenerCount { get; set; }//This is a value element
[XmlElement("fastenerProperty")]
public List<FastenerProperty> FastenerProperties { get; set; } //This is an element, not an array
}
public class FastenerProperty
{
[XmlElement("propID")]
public ValueElement PropId { get; set; }//This is a value element
[XmlElement("propName")]
public ValueElement PropName { get; set; }//This is a value element
[XmlElement("propValue")]
public ValueElement PropValue { get; set; }//This is a value element
}
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 have the following xml structure im trying to deserialize into a c# object:
<leagueTable>
<competition>Calor League Division One Central</competition>
<description>League Table</description>
<team>
<position>1</position>
<name>Barton Rovers</name>
<played>13</played>
<won>8</won>
<drawn>3</drawn>
<lost>2</lost>
<for>25</for>
<against>16</against>
<goalDifference>+9</goalDifference>
<points>27</points>
</team>
<team>
......
</team>
<team>
.....
</team>
</leagueTable>
and have created two classes for them to be deserialized into which are as follows
public class leagueTable
{
public string competition { get; set; }
public string description { get; set; }
[XmlElement("team")]
public List<team> TeamsList { get; set; }
}
and
[Serializable()]
public class team
{
public int position { get; set; }
public String name { get; set; }
public int played { get; set; }
public int won { get; set; }
public int drawn { get; set; }
public int lost { get; set; }
[XmlElement("for")]
public int goalsfor { get; set; }
[XmlElement("against")]
public int goalsagainst { get; set; }
[XmlElement("goalDifference")]
public int goaldifference { get; set; }
public int points { get; set; }
}
What i cant seem to figure out is how to get the teams deserialized into a list object. When the deserialization happens the competition and description properties are populated, however the teamslist list object is null. i have tried a number of different ways to create the property but each either fail or just stay as null. I have followed a number of different posts on here and on the web but no matter what i try it still fails to be populated.
For completeness this is the deserialisation code, edited to show xml setting
XmlSerializer serializer = new XmlSerializer(typeof(leagueTable));
leagueTable league = null;
Stream xmldoc = response.GetResponseStream();
XmlReaderSettings xmlsettings = new XmlReaderSettings();
xmlsettings.DtdProcessing = DtdProcessing.Parse;
using (XmlReader reader = XmlReader.Create(xmldoc, xmlsettings))
{
league = (leagueTable)serializer.Deserialize(reader);
}
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;
}
}
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.