Populate Observable collection from XML file in project (WPF) - c#

I Have XML file in my project
Here is it
<?xml version="1.0"?>
<catalog>
<car id="1">
<model>Scoda Fabia</model>
<year>2011</year>
<producer>Folkwagen</producer>
<price>6000</price>
<owner>Bil Johnson</owner>
<tel>+5810456455456</tel>
<mileage>670000</mileage>
<registered>USA</registered>
<image>Fabia1.JPG</image>
</car>
<car id="2">
<model>Huindai Getz</model>
<year>2008</year>
<producer>Huindai</producer>
<price>5000</price>
<owner>Dimitrious Gregorakis</owner>
<tel>+5810456445456</tel>
<mileage>120000</mileage>
<registered>USA</registered>
<image>hyundai_getz2.jpg</image>
</car>
<car id="3">
<model>Huindai i108</model>
<year>2014</year>
<producer>Huindai</producer>
<price>15000</price>
<owner>Dex Dexter</owner>
<tel>+5815556445456</tel>
<mileage>30000</mileage>
<registered>Canada</registered>
<image>hyundaii108.jpg</image>
</car>
<car id="4">
<model>Aveo</model>
<year>2000</year>
<producer>Shevrole</producer>
<price>3500</price>
<owner>Ivan Ivanov</owner>
<tel>+5815556445477</tel>
<mileage>300000</mileage>
<registered>Mexico</registered>
<image>aveo.jpg</image>
</car>
</catalog>
I created a class from it, here is code for class
[XmlRoot(ElementName = "car")]
public class Car
{
[XmlElement(ElementName = "model")]
public string Model { get; set; }
[XmlElement(ElementName = "year")]
public string Year { get; set; }
[XmlElement(ElementName = "producer")]
public string Producer { get; set; }
[XmlElement(ElementName = "price")]
public string Price { get; set; }
[XmlElement(ElementName = "owner")]
public string Owner { get; set; }
[XmlElement(ElementName = "tel")]
public string Tel { get; set; }
[XmlElement(ElementName = "mileage")]
public string Mileage { get; set; }
[XmlElement(ElementName = "registered")]
public string Registered { get; set; }
[XmlElement(ElementName = "image")]
public string Image { get; set; }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
}
[XmlRoot(ElementName = "catalog")]
public class Catalog
{
[XmlElement(ElementName = "car")]
public List<Car> Car { get; set; }
}
And Created ViewModel for it, where I defined observable collection anв define a method to fill it with data from XML
public class CarViewModel
{
public ObservableCollection<List<Car>> car { get; set; }
public void LoadCars()
{
Car = new ObservableCollection<List<Car>>();
var path = #"xml\CarsDatabase.xml";
using (TextReader reader = new StreamReader(path))
{
XmlSerializer serializer = new XmlSerializer(typeof(Catalog));
return (Catalog)serializer.Deserialize(reader);
}
}
}
In method LoadCars I need to fill car observable collections with data in my file, that is inside of the project.
How I can do this correctly?
Thank's for help.
UPDATE
I try to use this method
public void LoadCars()
{
Car = new ObservableCollection<List<Car>>();
var path = #"xml\CarsDatabase.xml";
using (TextReader reader = new StreamReader(path))
{
XmlSerializer serializer = new XmlSerializer(typeof(Catalog));
return (Catalog)serializer.Deserialize(reader);
}
}
But now I have error
Severity Code Description Project File Line Suppression State
Error CS0127 Since 'CarViewModel.LoadCars()' returns void, a return keyword must not be followed by an object expression DaxxTest C:\Users\nemes\Source\Repos\daxx_test\DaxxTest\DaxxTest\ViewModels\CarViewModel.cs 25 Active

Change
public ObservableCollection<List<Car>> car { get; set; }
to
public ObservableCollection<Car> car { get; set; }
And use XmlSerializer to serialize your xml information. Check bellow code for an example:
public ObservableCollection<Car> cars { get; set; }
public void LoadCars()
{
XmlSerializer serializer = new XmlSerializer(typeof(Catalog));
StreamReader reader = new StreamReader("CarsDatabase.xml");
var catalog = (Catalog)serializer.Deserialize(reader);
cars = new ObservableCollection<Car>(catalog.Car);
reader.Close();
}
[Serializable()]
public class Car
{
[XmlElement(ElementName = "model")]
public string Model { get; set; }
[XmlElement(ElementName = "year")]
public string Year { get; set; }
[XmlElement(ElementName = "producer")]
public string Producer { get; set; }
[XmlElement(ElementName = "price")]
public string Price { get; set; }
[XmlElement(ElementName = "owner")]
public string Owner { get; set; }
[XmlElement(ElementName = "tel")]
public string Tel { get; set; }
[XmlElement(ElementName = "mileage")]
public string Mileage { get; set; }
[XmlElement(ElementName = "registered")]
public string Registered { get; set; }
[XmlElement(ElementName = "image")]
public string Image { get; set; }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
}
[Serializable()]
[XmlRootAttribute("catalog", Namespace = "", IsNullable = false)]
public class Catalog
{
[XmlElement(ElementName = "car")]
public List<Car> Car { get; set; }
}

Related

Getting error "System.InvalidOperationException. There is an error in XML document (1, 2)." during Deserialization in C#

Trying to Deserialise XML response to C#. but getting error as specified below.
My code:
IRestResponse result = Client.Execute<StudentPersonal>(new RestRequest(Method.POST)
.AddHeader("Accept", " application/xml")
.AddHeader("Authorization", "Basic Y2xaTWNqZFFlbFF4YVU1TlFtUnZOV3hXTkhadmNHaFhPSGxTT0Rka1VIcFhhRTl5TWtWQ05rRjNUMlp5VlUxWlNYa3hjbEU1V1RGUmMxTkNOMlZWVlRvNk9nPT06eUkxdERIanNVcGxLUUpzUlNXNTVacXpRVUFGQ3JrZzFwUGxUbDhUTmRQaFU0Z0xsTFJlQkVxTmhzZml3TnpaVA==")
.AddHeader("Content-Type", "application/xml")
.AddParameter("application/xml", body, ParameterType.RequestBody));
StudentPersonal firstResponse = new StudentPersonal();
StringReader srt = new StringReader(result.Content);
XmlSerializer serializer = new XmlSerializer(typeof(StudentPersonal), new XmlRootAttribute("StudentPersonal"));
firstResponse = (StudentPersonal)serializer.Deserialize(srt);
Console.WriteLine(firstResponse);
Assert.AreEqual("Created", result.StatusCode.ToString());
My classes:
[XmlRoot(ElementName = "StudentPersonal")]
public class StudentPersonal
{
//// XmlSerializer serializer = new XmlSerializer(typeof(StudentPersonal));
//// using (StringReader reader = new StringReader(xml))
//// {
//// var test = (StudentPersonal)serializer.Deserialize(reader);
//// }
[XmlElement(ElementName = "LocalId")]
public double LocalId { get; set; }
[XmlElement(ElementName = "StateProvinceId")]
public int StateProvinceId { get; set; }
[XmlElement(ElementName = "ElectronicIdList")]
public object ElectronicIdList { get; set; }
[XmlElement(ElementName = "OtherIdList")]
public OtherIdList OtherIdList { get; set; }
[XmlElement(ElementName = "PersonInfo")]
public PersonInfo PersonInfo { get; set; }
[XmlElement(ElementName = "GiftedTalented")]
public string GiftedTalented { get; set; }
[XmlElement(ElementName = "EconomicDisadvantage")]
public string EconomicDisadvantage { get; set; }
[XmlElement(ElementName = "ESL")]
public string ESL { get; set; }
[XmlElement(ElementName = "YoungCarersRole")]
public string YoungCarersRole { get; set; }
[XmlElement(ElementName = "Disability")]
public string Disability { get; set; }
[XmlElement(ElementName = "IntegrationAide")]
public string IntegrationAide { get; set; }
[XmlElement(ElementName = "EducationSupport")]
public string EducationSupport { get; set; }
[XmlElement(ElementName = "Sensitive")]
public string Sensitive { get; set; }
[XmlAttribute(AttributeName = "xsd")]
public string Xsd { get; set; }
[XmlAttribute(AttributeName = "xsi")]
public string Xsi { get; set; }
[XmlAttribute(AttributeName = "RefId")]
public string RefId { get; set; }
[XmlAttribute(AttributeName = "xmlns")]
public string Xmlns { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName = "OtherId")]
public class OtherId
{
[XmlAttribute(AttributeName = "Type")]
public string Type { get; set; }
[XmlText]
public int Text { get; set; }
}
[XmlRoot(ElementName = "OtherIdList")]
public class OtherIdList
{
[XmlElement(ElementName = "OtherId")]
public List<OtherId> OtherId { get; set; }
}
[XmlRoot(ElementName = "Name")]
public class Name
{
[XmlElement(ElementName = "Title")]
public string Title { get; set; }
[XmlElement(ElementName = "FamilyName")]
public string FamilyName { get; set; }
[XmlElement(ElementName = "GivenName")]
public string GivenName { get; set; }
[XmlElement(ElementName = "MiddleName")]
public string MiddleName { get; set; }
[XmlElement(ElementName = "FamilyNameFirst")]
public string FamilyNameFirst { get; set; }
[XmlElement(ElementName = "PreferredFamilyName")]
public string PreferredFamilyName { get; set; }
[XmlElement(ElementName = "PreferredFamilyNameFirst")]
public string PreferredFamilyNameFirst { get; set; }
[XmlElement(ElementName = "PreferredGivenName")]
public string PreferredGivenName { get; set; }
[XmlElement(ElementName = "FullName")]
public string FullName { get; set; }
[XmlAttribute(AttributeName = "Type")]
public string Type { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName = "EnglishProficiency")]
public class EnglishProficiency
{
[XmlElement(ElementName = "Code")]
public int Code { get; set; }
}
[XmlRoot(ElementName = "Language")]
public class Language
{
[XmlElement(ElementName = "Code")]
public int Code { get; set; }
[XmlElement(ElementName = "LanguageType")]
public int LanguageType { get; set; }
}
[XmlRoot(ElementName = "LanguageList")]
public class LanguageList
{
[XmlElement(ElementName = "Language")]
public List<Language> Language { get; set; }
}
[XmlRoot(ElementName = "DwellingArrangement")]
public class DwellingArrangement
{
[XmlElement(ElementName = "Code")]
public int Code { get; set; }
}
[XmlRoot(ElementName = "Religion")]
public class Religion
{
[XmlElement(ElementName = "Code")]
public int Code { get; set; }
}
[XmlRoot(ElementName = "ReligiousEvent")]
public class ReligiousEvent
{
[XmlElement(ElementName = "Type")]
public string Type { get; set; }
[XmlElement(ElementName = "Date")]
public DateTime Date { get; set; }
}
[XmlRoot(ElementName = "ReligiousEventList")]
public class ReligiousEventList
{
[XmlElement(ElementName = "ReligiousEvent")]
public ReligiousEvent ReligiousEvent { get; set; }
}
[XmlRoot(ElementName = "Demographics")]
public class Demographics
{
[XmlElement(ElementName = "IndigenousStatus")]
public int IndigenousStatus { get; set; }
[XmlElement(ElementName = "Sex")]
public int Sex { get; set; }
[XmlElement(ElementName = "BirthDate")]
public DateTime BirthDate { get; set; }
[XmlElement(ElementName = "BirthDateVerification")]
public int BirthDateVerification { get; set; }
[XmlElement(ElementName = "CountryArrivalDate")]
public DateTime CountryArrivalDate { get; set; }
[XmlElement(ElementName = "EnglishProficiency")]
public EnglishProficiency EnglishProficiency { get; set; }
[XmlElement(ElementName = "LanguageList")]
public LanguageList LanguageList { get; set; }
[XmlElement(ElementName = "DwellingArrangement")]
public DwellingArrangement DwellingArrangement { get; set; }
[XmlElement(ElementName = "Religion")]
public Religion Religion { get; set; }
[XmlElement(ElementName = "ReligiousEventList")]
public ReligiousEventList ReligiousEventList { get; set; }
[XmlElement(ElementName = "PermanentResident")]
public string PermanentResident { get; set; }
[XmlElement(ElementName = "VisaSubClass")]
public int VisaSubClass { get; set; }
[XmlElement(ElementName = "VisaStatisticalCode")]
public string VisaStatisticalCode { get; set; }
[XmlElement(ElementName = "VisaExpiryDate")]
public DateTime VisaExpiryDate { get; set; }
[XmlElement(ElementName = "LBOTE")]
public string LBOTE { get; set; }
[XmlElement(ElementName = "ImmunisationCertificateStatus")]
public string ImmunisationCertificateStatus { get; set; }
[XmlElement(ElementName = "CulturalBackground")]
public int CulturalBackground { get; set; }
[XmlElement(ElementName = "MaritalStatus")]
public int MaritalStatus { get; set; }
[XmlElement(ElementName = "MedicareNumber")]
public int MedicareNumber { get; set; }
}
[XmlRoot(ElementName = "PhoneNumber")]
public class PhoneNumber
{
[XmlElement(ElementName = "Number")]
public int Number { get; set; }
[XmlElement(ElementName = "ListedStatus")]
public string ListedStatus { get; set; }
[XmlAttribute(AttributeName = "Type")]
public int Type { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName = "PhoneNumberList")]
public class PhoneNumberList
{
[XmlElement(ElementName = "PhoneNumber")]
public PhoneNumber PhoneNumber { get; set; }
}
[XmlRoot(ElementName = "Email")]
public class Email
{
[XmlAttribute(AttributeName = "Type")]
public int Type { get; set; }
[XmlText]
public string Text { get; set; }
}
[XmlRoot(ElementName = "EmailList")]
public class EmailList
{
[XmlElement(ElementName = "Email")]
public List<Email> Email { get; set; }
}
[XmlRoot(ElementName = "PersonInfo")]
public class PersonInfo
{
[XmlElement(ElementName = "Name")]
public Name Name { get; set; }
[XmlElement(ElementName = "Demographics")]
public Demographics Demographics { get; set; }
[XmlElement(ElementName = "AddressList")]
public object AddressList { get; set; }
[XmlElement(ElementName = "PhoneNumberList")]
public PhoneNumberList PhoneNumberList { get; set; }
[XmlElement(ElementName = "EmailList")]
public EmailList EmailList { get; set; }
}
Below is the response XML details from Result.content:
<StudentPersonal xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" RefId=\"9ec476fd-09b5-4b2b-967a-fb80b207526e\" xmlns=\"http://www.sifassociation.org/datamodel/au/3.4\">
<LocalId>2432717276450097998</LocalId>
<StateProvinceId>674361</StateProvinceId>
<ElectronicIdList />
<OtherIdList>
<OtherId Type=\"MazeKey\">674363</OtherId>
<OtherId Type=\"VETUSI\">674362</OtherId>
<OtherId Type=\"UPN\">674363</OtherId>
</OtherIdList>
<PersonInfo>
<Name Type=\"LGL\">
<Title>Ms</Title>
<FamilyName>Gutteridge2</FamilyName>
<GivenName>Ferdinanda2</GivenName>
<MiddleName>Creamer1</MiddleName>
<FamilyNameFirst>N</FamilyNameFirst>
<PreferredFamilyName>Gutteridge</PreferredFamilyName>
<PreferredFamilyNameFirst>N</PreferredFamilyNameFirst>
<PreferredGivenName>Ferdinanda</PreferredGivenName>
<FullName> Ferdinanda Gutteridge</FullName>
</Name>
<Demographics>
<IndigenousStatus>1</IndigenousStatus>
<Sex>2</Sex>
<BirthDate>2006-03-21</BirthDate>
<BirthDateVerification>1004</BirthDateVerification>
<CountryArrivalDate>2008-09-17</CountryArrivalDate>
<EnglishProficiency>
<Code>1</Code>
</EnglishProficiency>
<LanguageList>
<Language>
<Code>1201</Code>
<LanguageType>3</LanguageType>
</Language>
<Language>
<Code>4303</Code>
<LanguageType>1</LanguageType>
</Language>
<Language>
<Code>4303</Code>
<LanguageType>1</LanguageType>
</Language>
</LanguageList>
<DwellingArrangement>
<Code>1671</Code>
</DwellingArrangement>
<Religion>
<Code>0002</Code>
</Religion>
<ReligiousEventList>
<ReligiousEvent>
<Type>Confirmation</Type>
<Date>2018-07-17</Date>
</ReligiousEvent>
</ReligiousEventList>
<PermanentResident>P</PermanentResident>
<VisaSubClass>124</VisaSubClass>
<VisaStatisticalCode>VisaStatisticalCode</VisaStatisticalCode>
<VisaExpiryDate>2019-01-17</VisaExpiryDate>
<LBOTE>N</LBOTE>
<ImmunisationCertificateStatus>C</ImmunisationCertificateStatus>
<CulturalBackground>0901</CulturalBackground>
<MaritalStatus>3</MaritalStatus>
<MedicareNumber>67436</MedicareNumber>
</Demographics>
<AddressList />
<PhoneNumberList>
<PhoneNumber Type=\"0350\">
<Number>12367436</Number>
<ListedStatus>U</ListedStatus>
</PhoneNumber>
</PhoneNumberList>
<EmailList>
<Email Type=\"01\">person67436#email1.com.au</Email>
<Email Type=\"02\">person67436#email2.com.au</Email>
<Email Type=\"03\">person67436#email3.com.au</Email>
</EmailList>
</PersonInfo>
<GiftedTalented>N</GiftedTalented>
<EconomicDisadvantage>N</EconomicDisadvantage>
<ESL>N</ESL>
<YoungCarersRole>N</YoungCarersRole>
<Disability>N</Disability>
<IntegrationAide>N</IntegrationAide>
<EducationSupport>U</EducationSupport>
<Sensitive>N</Sensitive>
</StudentPersonal>
Error is from the above XML response. Getting Error
There is an error in XML document (1, 2). InvalidOperationException: <StudentPersonal xmlns='http://www.sifassociation.org/datamodel/au/3.4'> was not expected.
There seems to be two issues.
Add the namespace to your class:
[XmlRoot(ElementName = "StudentPersonal", Namespace = "http://www.sifassociation.org/datamodel/au/3.4")]
public class StudentPersonal
...
In the XML, all " are escaped with \.
<StudentPersonal xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" RefId=\"9ec476fd-09b5-4b2b-967a-fb80b207526e\" xmlns=\"http://www.sifassociation.org/datamodel/au/3.4\">
...
</StudentPersonal>
This also occurs in other places throughout the XML. Such as:
<PhoneNumber Type=\"0350\">
To resolve the issue, replace all occurrences of \" with ".
<StudentPersonal xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" RefId="9ec476fd-09b5-4b2b-967a-fb80b207526e" xmlns="http://www.sifassociation.org/datamodel/au/3.4">
...
</StudentPersonal>
and
<PhoneNumber Type="0350">
Here's a method that can be used to deserialize the XML:
DeserializeXMLStringToObject:
public static T DeserializeXMLStringToObject<T>(string xmlData)
{
T rObject = default(T);
try
{
if (string.IsNullOrEmpty(xmlData))
{
return default(T);
}
//replace \" with "
string xmlDataSanitized = xmlData.Replace("\\\"", "\"");
using (System.IO.StringReader reader = new System.IO.StringReader(xmlDataSanitized))
{
//add the namespace to the class instead of adding it here
//System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T), "http://www.sifassociation.org/datamodel/au/3.4");
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
rObject = (T)serializer.Deserialize(reader);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
throw ex;
}
return rObject;
}
Usage:
private StudentPersonal _studentPersonal = null;
...
_studentPersonal = DeserializeXMLStringToObject<StudentPersonal>(result.Content);
//for testing, display some of the data
//System.Diagnostics.Debug.WriteLine("LocalId: " + _studentPersonal.LocalId);
//System.Diagnostics.Debug.WriteLine("GivenName: " + _studentPersonal.PersonInfo.Name.GivenName);

C# xml deserialization won't pick up child elements into list

I can't figure out why this doesn't work, I searched for answer and when I sum up everything this should work but somehow it doesn't. So I have a Bill class which has some properties that are deserialized fine, but I have property List articles which comes up empty.
past of Bill class
[Serializable()]
[XmlRoot("Bills")]
public class Bill
{
private DateTime dateTimePrivate;
**[XmlArray("Bill")]
[XmlArrayItem("Article", typeof(Article))]
public List<Article> articles { get; set; }**
[XmlAttribute("User")]
public string user { get; set; } //Username
[XmlAttribute("Total")]
public int totalPrice { get; set; }
[XmlAttribute("ID")]
public int id { get; set; }
Article class
[Serializable()]
[XmlRoot("Article")]
public class Article
{
[XmlAttribute("ID")]
public int ID { get; set; }
[XmlAttribute("name")]
public string name { get; set; }
[XmlAttribute("buttonName")]
public string buttonName { get; set; }
[XmlAttribute("price")]
public float price { get; set; }
[XmlAttribute("quantity")]
public float quantity { get; set; } //Namijenjeno samo za racune
[XmlAttribute("totalPrice")]
public float totalPrice { get { return price * quantity; } set { totalPrice = price * quantity; } }
AllBIlls.xml
<?xml version="1.0" encoding="utf-8"?>
<BillsCollection>
<Bills>
<Bill ID="0" Time="06-12-2020 13:28" User="TEST" SavedToDatabase="TEST" Total="24">
<Article ID="0" name="CocaCola" quantity="1" price="12" totalPrice="12" />
<Article ID="1" name="Sprite" quantity="1" price="12" totalPrice="12" />
</Bill>
<Bill ID="1" Time="06-12-2020 13:28" User="TEST" SavedToDatabase="TEST" Total="36">
<Article ID="0" name="CocaCola" quantity="2" price="12" totalPrice="24" />
<Article ID="1" name="Sprite" quantity="1" price="12" totalPrice="12" />
</Bill>
</Bills>
</BillsCollection>
Deserialization
public static BillList GetBills()
{
Console.WriteLine("reading bills");
BillList allBills = null;
//Adding root element for serialziation
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "BillsCollection";
xRoot.IsNullable = true;
XmlSerializer serializer = new XmlSerializer(typeof(BillList), xRoot);
XmlReader reader = AllBillsXml.CreateReader();
allBills = (BillList)serializer.Deserialize(reader);
reader.Close();
Console.WriteLine("reading succesful");
return allBills;
}
I used this site https://json2csharp.com/xml-to-csharp along with the xml you provided and i can deserialize the Articles collection just fine.
Here are the classes generated:
// using System.Xml.Serialization;
// XmlSerializer serializer = new XmlSerializer(typeof(BillsCollection));
// using (StringReader reader = new StringReader(xml))
// {
// var test = (BillsCollection)serializer.Deserialize(reader);
// }
[XmlRoot(ElementName = "Article")]
public class Article
{
[XmlAttribute(AttributeName = "ID")]
public String ID { get; set; }
[XmlAttribute(AttributeName = "name")]
public String Name { get; set; }
[XmlAttribute(AttributeName = "quantity")]
public String Quantity { get; set; }
[XmlAttribute(AttributeName = "price")]
public String Price { get; set; }
[XmlAttribute(AttributeName = "totalPrice")]
public String TotalPrice { get; set; }
}
[XmlRoot(ElementName = "Bill")]
public class Bill
{
[XmlElement(ElementName = "Article")]
public List<Article> Article { get; set; }
[XmlAttribute(AttributeName = "ID")]
public String ID { get; set; }
[XmlAttribute(AttributeName = "Time")]
public String Time { get; set; }
[XmlAttribute(AttributeName = "User")]
public String User { get; set; }
[XmlAttribute(AttributeName = "SavedToDatabase")]
public String SavedToDatabase { get; set; }
[XmlAttribute(AttributeName = "Total")]
public String Total { get; set; }
}
[XmlRoot(ElementName = "Bills")]
public class Bills
{
[XmlElement(ElementName = "Bill")]
public List<Bill> Bill { get; set; }
}
[XmlRoot(ElementName = "BillsCollection")]
public class BillsCollection
{
[XmlElement(ElementName = "Bills")]
public Bills Bills { get; set; }
}
And here is the Articles object filled :
And here's the deserialization code :
XmlSerializer serializer = new XmlSerializer(typeof(BillsCollection));
using (StreamReader reader = new StreamReader(#"Path to xml.xml"))
{
var test = (BillsCollection)serializer.Deserialize(reader);
}
Using the "System.Xml.Serialization" namespace
Did you tried using XmlTextReader instead of XmlReader? This might help you.

Deserialize XML with list of elements where some are xsi:nil=“true”

When I deserialize the XML below, from a third-party, my objects are always null.
XML
<?xml version="1.0"?>
<OrderImport xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Reply i:nil="true">
</Reply>
<ReplyStatus i:nil="true">
<DebugInfo>
</DebugInfo>
<PerformanceLogInfo>
</PerformanceLogInfo>
</ReplyStatus>
<Reply>
<OrderNumber>4063286</OrderNumber>
</Reply>
<ReplyStatus>
<Result>0</Result>
<Message>
</Message>
</ReplyStatus>
</OrderImport>
C# Class
[XmlRoot(ElementName = "OrderImport")]
public class OrderImport
{
[XmlElement(ElementName = "Reply")]
public List<Reply> Reply { get; set; }
[XmlElement(ElementName = "ReplyStatus")]
public List<ReplyStatus> ReplyStatus { get; set; }
[XmlAttribute(AttributeName = "i", Namespace = "http://www.w3.org/2000/xmlns/")]
public string I { get; set; }
}
[XmlRoot(ElementName= "Reply")]
public class Reply
{
[XmlAttribute(AttributeName = "nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string Nil { get; set; }
[XmlElement(ElementName = "OrderNumber")]
public string OrderNumber { get; set; }
}
[XmlRoot(ElementName = "ReplyStatus")]
public class ReplyStatus
{
[XmlElement(ElementName = "DebugInfo")]
public string DebugInfo { get; set; }
[XmlElement(ElementName = "PerformanceLogInfo")]
public string PerformanceLogInfo { get; set; }
[XmlAttribute(AttributeName = "nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string Nil { get; set; }
[XmlElement(ElementName = "Result")]
public string Result { get; set; }
[XmlElement(ElementName = "Message")]
public string Message { get; set; }
}
I believe the problem has to do with the first occurrence of the objects Reply and ReplyStatus being null.
I'm trying to deserialize like so
httpResponseMessage.Content.ReadAsAsync<OrderImport>().Result;
However, I've found that if I deserialize like this it works just fine
stringres = httpResponseMessage.Content.ReadAsStringAsync().Result;
using (var stringreader = new StringReader(stringres))
{
var result = (OrderImport)xmlSerializer.Deserialize(stringreader);
}

Deserializing xml returns zero elements

This is my xml:
<?xml version="1.0"?>
<orders>
<order>
<customer_id>5675757</customer_id>
<order_code>6456</order_code>
<products>
<product>
<product_item_code>577868</product_item_code>
<product_item_amount>22</product_item_amount>
</product>
</products>
</order>
</orders>
And this is my class:
[XmlRoot(ElementName = "orders")]
public class Orders
{
public List<OrderModel> OrdersList { get; set; }
}
[XmlRoot(ElementName = "order")]
public class OrderModel
{
[XmlElement(ElementName = "customer_id")]
public string CustomerId { get; set; }
[XmlElement(ElementName = "order_code")]
public string OrderCode { get; set; }
[XmlElement(ElementName = "products")]
public List<Product> products { get; set; }
}
[XmlRoot(ElementName = "product")]
public class Product
{
[XmlElement(ElementName = "product_item_code")]
public string product_item_code { get; set; }
[XmlElement(ElementName = "product_item_amount")]
public string product_item_amount { get; set; }
}
And this is my code:
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
var serializer = new XmlSerializer(typeof(Orders));
var orders = (Orders)serializer.Deserialize(fileStream);
}
But it returns 0 elements. I know I am missing something obvious but I don't know what.
Change you class Orders and OrderModel:
[XmlRoot(ElementName = "orders")]
public class Orders
{
[XmlElement(ElementName = "order")]
public List<OrderModel> OrdersList { get; set; }
}
[XmlRoot(ElementName = "order")]
public class OrderModel
{
[XmlElement(ElementName = "customer_id")]
public string CustomerId { get; set; }
[XmlElement(ElementName = "order_code")]
public string OrderCode { get; set; }
[XmlArray(ElementName = "products")]
[XmlArrayItem(ElementName = "product")]
public List<Product> products { get; set; }
}
Then it should work
Modify your classes as below and it will work.
[XmlRoot(ElementName = "orders")]
public class Orders
{
[XmlElement(ElementName = "order")]
public List<OrderModel> OrdersList { get; set; }
}
public class OrderModel
{
[XmlElement(ElementName = "customer_id")]
public string CustomerId { get; set; }
[XmlElement(ElementName = "order_code")]
public string OrderCode { get; set; }
[XmlArray(ElementName = "products")]
[XmlArrayItem(ElementName = "product")]
public List<Product> products { get; set; }
}
public class Product
{
[XmlElement(ElementName = "product_item_code")]
public string product_item_code { get; set; }
[XmlElement(ElementName = "product_item_amount")]
public string product_item_amount { get; set; }
}

C# - How to deserialize xml response

I am retrieving xml data from an web api and deserializing the data into objects.:
<Result>
<VendorInfo xml:lang="xx">
<Vendor vname="A" cpe="B">
<Product pname="C" cpe="D"/>
</Vendor>
<Vendor vname="E" cpe="F">
<Product pname="G" cpe="H"/>
</Vendor>
<Vendor vname="I" cpe="J">
<Product pname="K" cpe="L"/>
<Product pname="M" cpe="N"/>
</Vendor>
</VendorInfo>
<Status keyword="hoge" feed="bar"/>
</Result>
My current code is this:
[XmlRoot(ElementName = "Product")]
public class Product
{
[XmlAttribute(AttributeName = "pname")]
public string Pname { get; set; }
[XmlAttribute(AttributeName = "cpe")]
public string Cpe { get; set; }
}
[XmlRoot(ElementName = "Vendor")]
public class Vendor
{
[XmlArrayItem(ElementName = "Product")]
public List<Product> Product { get; set; }
[XmlAttribute(AttributeName = "vname")]
public string Vname { get; set; }
[XmlAttribute(AttributeName = "cpe")]
public string Cpe { get; set; }
}
[XmlRoot(ElementName = "VendorInfo")]
public class VendorInfo
{
[XmlElement(ElementName = "Vendor")]
public List<Vendor> Vendor { get; set; }
[XmlAttribute(AttributeName = "lang")]
public string Lang { get; set; }
}
[XmlRoot(ElementName = "Status")]
public class Status
{
[XmlAttribute(AttributeName = "feed")]
public string Feed { get; set; }
[XmlAttribute(AttributeName = "keyword")]
public string Keyword { get; set; }
}
[XmlRoot(ElementName = "Result")]
public class Result
{
[XmlElement(ElementName = "VendorInfo")]
public VendorInfo VendorInfo { get; set; }
[XmlElement(ElementName = "Status")]
public Status Status { get; set; }
}
But, This code does not working correctly.
Only first 2 Vendor elements are deserialized, Product element is not deserialized.
What am i doing wrong?
best regards
You have few things to be taken care.
Make only one element XmlRoot. Refer below link and search for "Controlling Serialization of Classes Using XmlRootAttribute and XmlTypeAttribute".
https://learn.microsoft.com/en-us/dotnet/standard/serialization/controlling-xml-serialization-using-attributes
Here in your case, the "Result" class is root.
Make rest all XmlType.
In the vendor class instead of "XmlArrayItem", make it just "XmlElement".
Here is the working code.
[XmlType("Product")]
public class Product
{
[XmlAttribute(AttributeName = "pname")]
public string Pname { get; set; }
[XmlAttribute(AttributeName = "cpe")]
public string Cpe { get; set; }
}
[XmlType("Vendor")]
public class Vendor
{
[XmlElement(ElementName = "Product")]
public List<Product> Product { get; set; }
[XmlAttribute(AttributeName = "vname")]
public string Vname { get; set; }
[XmlAttribute(AttributeName = "cpe")]
public string Cpe { get; set; }
}
[XmlType("VendorInfo")]
public class VendorInfo
{
[XmlElement(ElementName = "Vendor")]
public List<Vendor> Vendor { get; set; }
[XmlAttribute(AttributeName = "xml:lang")]
public string Lang { get; set; }
}
[XmlType("Status")]
public class Status
{
[XmlAttribute(AttributeName = "feed")]
public string Feed { get; set; }
[XmlAttribute(AttributeName = "keyword")]
public string Keyword { get; set; }
}
[XmlRoot(ElementName = "Result")]
public class Result
{
[XmlElement(ElementName = "VendorInfo")]
public VendorInfo VendorInfo { get; set; }
[XmlElement(ElementName = "Status")]
public Status Status { get; set; }
}

Categories