I am load xml file like
<?xml version="1.0" encoding="UTF-8"?>
<OrderHeadUpload xmlns="http://www.sample-package.org" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Number>Z-00006453580748</Number>
<Number_confirm>000033477</Number_confirm>
<Positions>
<id>168816</Product_id>
<Tare_id>2442</Tare_id>
</Positions>
</OrderHeadUpload>
Make 2 class
[XmlRoot(ElementName = "Head", Namespace = "http://www.sample-package.org")]
public class OrderHeadUpload
{
[XmlElement(ElementName = "Number_confirm", Namespace = "http://www.sample-package.org")]
public string Client_id { get; set; }
[XmlElement(ElementName = "Number", Namespace = "http://www.sample-package.org")]
public string Barcode_id { get; set; }
}
[XmlRoot(ElementName = "Positions", Namespace = "http://www.sample-package.org")]
public class Positions
{
[XmlElement(ElementName = "id", Namespace = "http://www.sample-package.org")]
public string id { get; set; }
[XmlElement(ElementName = "Tare_id", Namespace = "http://www.sample-package.org")]
public string Tare_id {get; set;}
}
i am load xml file (temp.xml) then serializer on classes 2 Position and Head
then StringReader, which reads strings from a file
and then var position = (Positions) serializer.Deserialize (reader); class serialized become deserialized
doc.Load(temp);
XmlSerializer serializer = new XmlSerializer(typeof(Positions));
XmlSerializer serializer2 = new XmlSerializer(typeof(Head));
StringReader reader = new StringReader(temp);
var position = (Positions)serializer.Deserialize(reader);
var Head = (OrderHeadUpload)serializer2.Deserialize(reader);
but i see error
Error msg There is an error in XML document (1, 1).
Where?: at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)
at .cs:line 64 (var position = (Positions)serializer.Deserialize(reader);)
How to correctly deserialize this xml?
Try:
[XmlRoot(ElementName = "Positions", Namespace = "http://www.sample-package.org")]
public class Positions
{
[XmlElement(ElementName = "id", Namespace = "http://www.sample-package.org")]
public string id { get; set; }
[XmlElement(ElementName = "Tare_id", Namespace = "http://www.sample-package.org")]
public string Tare_id { get; set; }
}
[XmlRoot(ElementName = "Head", Namespace = "http://www.sample-package.org")]
public class OrderHeadUpload
{
[XmlElement(ElementName = "Number_confirm", Namespace = "http://www.sample-package.org")]
public string Client_id { get; set; }
[XmlElement(ElementName = "Number", Namespace = "http://www.sample-package.org")]
public string Barcode_id { get; set; }
[XmlElement(ElementName = "Positions")]
public Positions positions;
}
Use:
var order = (OrderHeadUpload)serializer.Deserialize(reader);
And you need to deserialize just onetime with OrderHeadUpload. If you have more than one Positions, you can declare like a List<T>
Related
please advice how do i map the response into class because from every example i came across body always don't have symbol like core:transactionResponse
my code:
string fileName = #"C:\Users\Lenovo\Downloads\GLResponseXml.xml";
XDocument xDoc = XDocument.Load(fileName);
var unwrappedResponse = xDoc.Descendants((XNamespace)"http://schemas.xmlsoap.org/soap/envelope/" + "Body")
.First()
.FirstNode;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(TransactionResponse));
TransactionResponse response = (TransactionResponse)xmlSerializer.Deserialize(xDoc.Descendants((XNamespace)"http://schemas.xmlsoap.org/soap/envelope/" + "Body")
.First()
.FirstNode
.CreateReader()
);
for deserealizing this soap xml:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dpss0="bons">
<soapenv:Header/>
<soapenv:Body>
<core:transactionResponse xmlns:bo="http://service.example.co.id/core/bo" xmlns:core="http://service.example.co.id/core">
<response>
<header>
<coreJournal>149326</coreJournal>
</header>
<content xsi:type="bo:OKMessage">
<message/>
</content>
</response>
</core:transactionResponse>
</soapenv:Body>
</soapenv:Envelope>
but i got this error: InvalidOperationException: <transactionResponse xmlns='http://service.example.co.id/core'> was not expected.
i'm mapping the response into this class:
public class GLXmlResponse
{
[XmlRoot(ElementName = "response")]
public class Response
{
[XmlElement(ElementName = "header")]
public Header Header { get; set; }
[XmlElement(ElementName = "content")]
public Content Content { get; set; }
}
[XmlRoot(ElementName = "header")]
public class Header
{
[XmlElement(ElementName = "coreJournal")]
public string CoreJournal { get; set; }
}
[XmlRoot(ElementName = "content")]
public class Content
{
[XmlElement(ElementName = "message")]
public string Message { get; set; }
[XmlAttribute(AttributeName = "type", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string Type { get; set; }
}
[XmlRoot(ElementName = "transactionResponse", Namespace = "http://service.example.co.id/core")]
public class TransactionResponse
{
[XmlElement(ElementName = "response")]
public Response Response { get; set; }
[XmlAttribute(AttributeName = "bo", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Bo { get; set; }
[XmlAttribute(AttributeName = "core", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Core { get; set; }
}
[XmlRoot(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Body
{
[XmlElement(ElementName = "transactionResponse", Namespace = "http://service.example.co.id/core")]
public TransactionResponse TransactionResponse { get; set; }
}
[XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope
{
[XmlElement(ElementName = "Header", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public string Header { get; set; }
[XmlElement(ElementName = "Body", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public Body Body { get; set; }
[XmlAttribute(AttributeName = "soapenv", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Soapenv { get; set; }
[XmlAttribute(AttributeName = "soapenc", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Soapenc { get; set; }
[XmlAttribute(AttributeName = "xsd", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Xsd { get; set; }
[XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Xsi { get; set; }
[XmlAttribute(AttributeName = "dpss0", Namespace = "http://www.w3.org/2000/xmlns/")]
public string Dpss0 { get; set; }
}
}
need help on getting the class object right
I can't repro the exact error you're seeing, so you might want to check from a minimal repro; I'm using:
var env = (GLXmlResponse.Envelope)new XmlSerializer(typeof(GLXmlResponse.Envelope))
.Deserialize(new StringReader(xml));
System.Console.WriteLine(env.Body.TransactionResponse.Response.Header.CoreJournal);
where:
string xml = #"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:soapenc=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:dpss0=""bons"">
<soapenv:Header/>
<soapenv:Body>
<core:transactionResponse xmlns:bo=""http://service.example.co.id/core/bo"" xmlns:core=""http://service.example.co.id/core"">
<response>
<header>
<coreJournal>149326</coreJournal>
</header>
<content xsi:type=""bo:OKMessage"">
<message/>
</content>
</response>
</core:transactionResponse>
</soapenv:Body></soapenv:Envelope>";
which just has a null for .Response. The reason for that is that this is actually in the empty namespace (prefixes are not inherited), so you need
[XmlElement(ElementName = "response", Namespace = "")]
public Response Response { get; set; }
However, this then causes a problem with the OKMessage in the xml. If I comment out the <content>, then it works and I can see the output 149326.
However, it might be simpler to start by just copying the xml into the clipboard, Edit -> Paste Special -> Paste XML As Classes, and see what it generates, and work from there.
I'm getting XML Data which contains an "envelope". For brevity, I'm focused on "Custom Fields" which is a collection of "Field".
Here is the part of the class definitions giving me a problem:
namespace Model.DocuSignEnvelope
{
[XmlRoot(ElementName = "CustomFields", Namespace = "http://www.docusign.net/API/3.0")]
public class CustomFields
{
[XmlElement(ElementName = "CustomField", Namespace = "http://www.docusign.net/API/3.0")]
public List<CustomField> CustomField { get; set; }
}
[XmlRoot(ElementName = "CustomField", Namespace = "http://www.docusign.net/API/3.0")]
public class CustomField
{
[XmlElement(ElementName = "Name", Namespace = "http://www.docusign.net/API/3.0")]
public string Name { get; set; } = "";
[XmlElement(ElementName = "Show", Namespace = "http://www.docusign.net/API/3.0")]
public string Show { get; set; } = "";
[XmlElement(ElementName = "Required", Namespace = "http://www.docusign.net/API/3.0")]
public string Required { get; set; } = "";
[XmlElement(ElementName = "Value", Namespace = "http://www.docusign.net/API/3.0")]
public string Value { get; set; } = "";
[XmlElement(ElementName = "CustomFieldType", Namespace = "http://www.docusign.net/API/3.0")]
public string CustomFieldType { get; set; } = "";
}
}
public static class DocuSignExtensionMethods
{
public static T DeserializeXmlX<T>(this string input) where T : class
{
XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(T));
using StringReader sr = new StringReader(input);
return (T)ser.Deserialize(sr);
}
}
if I get an empty list, happy times, it deserializes without issue:
<?xml version="1.0" encoding="utf-8"?>
<DocuSignEnvelopeInformation
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.docusign.net/API/3.0">
<EnvelopeStatus>
<RecipientStatuses>
<RecipientStatus>
<Type>Signer</Type>
...
<CustomFields />
...
but if I get a list of "empty" Custom Field
<?xml version="1.0" encoding="utf-8"?>
<DocuSignEnvelopeInformation
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.docusign.net/API/3.0">
<EnvelopeStatus>
<RecipientStatuses>
<RecipientStatus>
<Type>Signer</Type>
...
<CustomFields>
<CustomField />
<CustomField />
<CustomField />
</CustomFields>
...
It errors out with the Exception:
- ex {"There is an error in XML document (20, 7)."} System.Exception {System.InvalidOperationException}
- InnerException {"ReadElementContentAs() methods cannot be called on an element that has child elements. Line 20, position 7."} System.Exception {System.Xml.XmlException}
How can I tell the Deserializer to deserialize those fields as either an empty List (no valid entries) or a list with 3 empty CustomFields.
The following code works :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(EnvelopeInfo));
EnvelopeInfo fields = (EnvelopeInfo)serializer.Deserialize(reader);
}
}
[XmlRoot(ElementName = "EnvelopeInfo", Namespace = "http://www.docusign.net/API/3.0")]
public class EnvelopeInfo
{
[XmlElement(ElementName = "EnvelopeStatus", Namespace = "http://www.docusign.net/API/3.0")]
public EnvelopeStatus EnvelopeStatus { get; set; }
}
public class EnvelopeStatus
{
[XmlArray(ElementName = "RecipientStatuses", Namespace = "http://www.docusign.net/API/3.0")]
[XmlArrayItem(ElementName = "RecipientStatus", Namespace = "http://www.docusign.net/API/3.0")]
public RecipientStatus[] RecipientStatus { get; set; }
}
public class RecipientStatus
{
[XmlElement(ElementName = "CustomFields", Namespace = "http://www.docusign.net/API/3.0")]
public CustomFields CustomFields { get; set; }
}
public class CustomFields
{
[XmlElement(ElementName = "CustomField", Namespace = "http://www.docusign.net/API/3.0")]
public List<CustomField> CustomField { get; set; }
}
[XmlRoot(ElementName = "CustomField", Namespace = "http://www.docusign.net/API/3.0")]
public class CustomField
{
[XmlElement(ElementName = "Name", Namespace = "http://www.docusign.net/API/3.0")]
public string Name { get; set; }
[XmlElement(ElementName = "Show", Namespace = "http://www.docusign.net/API/3.0")]
public string Show { get; set; }
[XmlElement(ElementName = "Required", Namespace = "http://www.docusign.net/API/3.0")]
public string Required { get; set; }
[XmlElement(ElementName = "Value", Namespace = "http://www.docusign.net/API/3.0")]
public string Value { get; set; }
[XmlElement(ElementName = "CustomFieldType", Namespace = "http://www.docusign.net/API/3.0")]
public string CustomFieldType { get; set; }
}
}
Used following XML
<?xml version="1.0" encoding="utf-8"?>
<EnvelopeInfo xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.docusign.net/API/3.0">
<EnvelopeStatus>
<RecipientStatuses>
<RecipientStatus>
<Type>Signer</Type>
<CustomFields>
<CustomField />
<CustomField />
<CustomField />
</CustomFields>
</RecipientStatus>
</RecipientStatuses>
</EnvelopeStatus>
</EnvelopeInfo>
I'm still struggling with deserialization of XML containing arrays of items.
The response I want to deserialize:
<ns1:OperationResult xmlns:ns1="http://xxxx.com">
<done>false</done>
<errorEntities>
<elements>
<entityID>100014</entityID>
<entityType>GROUP</entityType>
<errors>
<errorCode>INVALID_DATA</errorCode>
<errorMessage>s: d3f62887-a2a3-4cde-8f8b-09812a7bd011ed8d385e-f4c4-4fae-9a4b-1ba405db54b6-MessageTemplate:{k2.constraints.numberFormat.length}|length:5|; </errorMessage>
</errors>
</elements>
</errorEntities>
</ns1:OperationResult>
And this is my corresponding class:
[XmlRootAttribute(Namespace = "http://xxxx.", IsNullable = false, ElementName = "OperationResult")]
public class GroupCreateUpdateResult
{
[XmlElement(ElementName = "done")]
public string done { get; set; }
[XmlElement(ElementName = "errorEntities")]
public ErrorEntities errorEntities { get; set; }
public bool hasErrors => done == "true" ? true : false;
}
[XmlRoot(ElementName = "errorEntities")]
public class ErrorEntities
{
[XmlElement(ElementName = "elements")]
public List<ErrorElements> elements { get; } = new List<ErrorElements>();
}
[XmlRoot(ElementName = "elements")]
public class ErrorElements
{
[XmlElement(ElementName = "entityId")]
public string entityId { get; set; }
[XmlElement(ElementName = "entityType")]
public string entityType { get; set; }
[XmlElement(ElementName = "errors")]
Errors errors { get; set; }
}
[XmlRoot(ElementName = "errors")]
public class Errors
{
[XmlElement(ElementName = "errorCode")]
public string errorCode { get; set; }
[XmlElement(ElementName = "errorMessage")]
public string errorMessage { get; set; }
}
I have already a method deserializing my responses. Actually I am struggling with this specific one. Alle others without arrays are working fine.
What I finally get is this:
Any advice is highly appreciated.
You have a few issues
1) The namespace in the xml and the classes have to be the same
2) The tags names in the classes are case sensitive so you have to make sure the spelling is correct (Upper/Lower Case)
3) The class object have to be public otherwise the tags are ignored.
4) Where there are no namespaces in XML (and parent has a namespace) you need the empty string for the namespaces
See corrected code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(GroupCreateUpdateResult));
GroupCreateUpdateResult group = (GroupCreateUpdateResult)serializer.Deserialize(reader);
}
}
[XmlRootAttribute(Namespace = "http://com.f24.soap.fwi.schema", IsNullable = false, ElementName = "OperationResult")]
public class GroupCreateUpdateResult
{
[XmlElement(ElementName = "done", Namespace = "")]
public string done { get; set; }
[XmlElement(ElementName = "errorEntities", Namespace = "")]
public ErrorEntities errorEntities { get; set; }
//public bool hasErrors => done == "true" ? true : false;
}
[XmlRoot(ElementName = "errorEntities")]
public class ErrorEntities
{
[XmlElement(ElementName = "elements", Namespace = "")]
public List<ErrorElements> elements { get; set;}
}
[XmlRoot(ElementName = "elements")]
public class ErrorElements
{
[XmlElement(ElementName = "entityID")]
public string entityId { get; set; }
[XmlElement(ElementName = "entityType")]
public string entityType { get; set; }
[XmlElement(ElementName = "errors", Namespace = "")]
public Errors errors { get; set; }
}
[XmlRoot(ElementName = "errors")]
public class Errors
{
[XmlElement(ElementName = "errorCode")]
public string errorCode { get; set; }
[XmlElement(ElementName = "errorMessage")]
public string errorMessage { get; set; }
}
}
I'm serialising class to specific XML format. Below is the class structure & code I've used to serialize it. Serailized file tend to miss element name "Address".
I've 3 classes StudentInfo which has two properties of type "Student" & "Address"
[Serializable]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRoot("StudentInfo", Namespace = "http://TestBizTalkMap.Student")]
public class StudentInfo
{
[System.Xml.Serialization.XmlElement("", Namespace = "")]
public Student Student { get; set; }
[System.Xml.Serialization.XmlElement("ns1", Namespace = "ns1:http://TestBizTalkMap.Address")]
public Address Address { get; set; }
}
[Serializable]
public class Student
{
public string EnrollNo { get; set; }
public string Name { get; set; }
public string BTSReceivedOn { get; set; }
}
[Serializable]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRoot("Address", Namespace = "http://TestBizTalkMap.Address")]
public class Address
{
[XmlElement("",Namespace="")]
public string City { get; set; }
[XmlElement("", Namespace = "")]
public string State { get; set; }
}
Code Used to serialze it:
public XmlDocument GetXMLSchema<T>(T type, string schemeNameSpace)
{
XmlDocument xmlDoc = new XmlDocument();
XmlSerializer xmlSerializer = new XmlSerializer(type.GetType());
try
{
using (MemoryStream xmlStream = new MemoryStream())
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("ns0", schemeNameSpace);
xmlSerializer.Serialize(xmlStream, type, ns);
xmlStream.Position = 0;
xmlDoc.Load(xmlStream);
if (xmlDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
{
xmlDoc.RemoveChild(xmlDoc.FirstChild);
}
}
}
catch (Exception ex)
{
throw ex;
}
return xmlDoc;
}
it serializes it to as
<ns0:StudentInfo xmlns:ns0="http://TestBizTalkMap.Student">
<Student>
<EnrollNo>EnrollNl</EnrollNo>
<Name>Name</Name>
<BTSReceivedOn>BTSReceivedOn</BTSReceivedOn>
</Student>
<ns1 xmlns="http://TestBizTalkMap.Address">
<City>City</City>
<State>State</State>
</ns1>
</ns0:StudentInfo
Whereas I want it to get serialised as
<ns0:StudentInfo xmlns:ns0="http://TestBizTalkMap.Student">
<Student>
<EnrollNo>EnrollNo_0</EnrollNo>
<Name>Name_0</Name>
<BTSReceivedOn>BTSReceivedOn_0</BTSReceivedOn>
</Student>
<ns1:Adress xmlns:ns1="http://TestBizTalkMap.Address">
<City>City_0</City>
<State>State_0</State>
</ns1:Adress>
</ns0:StudentInfo>
Any help?
Thanks
You seem to have got awfully confused between names and namespaces. The name of your Address element is Address, not ns1, and its namespace is http://TestBizTalkMap.Address, not ns1:http://TestBizTalkMap.Address.
This is all you need to generate the correct XML.
[XmlRoot(Namespace = "http://TestBizTalkMap.Student")]
public class StudentInfo
{
[XmlElement(Namespace = "")]
public Student Student { get; set; }
[XmlElement(Namespace = "http://TestBizTalkMap.Address")]
public Address Address { get; set; }
}
public class Student
{
public string EnrollNo { get; set; }
public string Name { get; set; }
public string BTSReceivedOn { get; set; }
}
public class Address
{
[XmlElement(Namespace = "")]
public string City { get; set; }
[XmlElement(Namespace = "")]
public string State { get; set; }
}
The namespace prefixes are unimportant, but if you really want them to be ns0 and ns1 then you can specify these via the XmlSerializerNamespaces you pass to the Serialize method:
var ns= new XmlSerializerNamespaces();
ns.Add("ns0", "http://TestBizTalkMap.Student");
ns.Add("ns1", "http://TestBizTalkMap.Address");
And if you don't want the XML Declaration, then don't load the resulting XML into an XmlDocument and remove it, just stop it being written in the first place using XmlWriterSettings:
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
// ...
};
See this fiddle for a working demo.
I am having trouble deserializing XML. I get AccountInformation to work but it won't work with the Leauge elements. The XML doesn't contain any tag for "Leauges" and I don't want to add that tag to get it to work. Is there any other way to "fix" it? I have tried diffrent solutions but the deserialized result of the leauges comes back empty. What am I missing?
Any help appreciated!
Se my code below:
Update:
I have modified the code and the XML but I won't work anyway. What am I missing here?
[Serializable]
[XmlRoot(ElementName = "LeaugeCollection", Namespace = "")]
public class LeagueCollection
{
[XmlArray("Leagues")]
[XmlArrayItem("League",typeof(League))]
public League[] League { get; set; }
[XmlElement(ElementName = "AccountInformation")]
public string AccountInformation { get; set; }
}
[Serializable()]
public class League
{
[XmlElement(ElementName = "Id")]
public int Id { get; set; }
[XmlElement(ElementName = "Name")]
public string Name { get; set; }
[XmlElement(ElementName = "Country")]
public string Country { get; set; }
[XmlElement(ElementName = "Historical_Data")]
public string Historical_Data { get; set; }
[XmlElement(ElementName = "Fixtures")]
public string Fixtures { get; set; }
[XmlElement(ElementName = "LiveScore")]
public string Livescore { get; set; }
[XmlElement(ElementName = "NumberOfMatches")]
public int NumberOfMatches { get; set; }
[XmlElement(ElementName = "LatestMatch")]
public DateTime LatestMatch { get; set; }
}
Deserialize code:
public static void Main(string[] args)
{
XmlSerializer deserializer = new XmlSerializer(typeof(LeagueCollection));
TextReader reader = new StreamReader(#"C:\XmlFiles\XmlSoccer.xml");
object obj = deserializer.Deserialize(reader);
LeagueCollection XmlData = (LeagueCollection)obj;
reader.Close();
}
Link to XML:
Thanks in advance!
The XML you have in the image is missing the actual array element (Leauges), it has only the array items elements (Leauge), that is why you cannot get it deserialized!
UPDATE:
Ok, trying to reproduce your code, I now see that in your XML your elements are spelled "League" while in your code "Leauge"
FIX that first!
UPDATE2:
After the edits you have done according to my comments,it seems to work fine!
You are missing a namespace. I don't like both Leagues and League. Leagues is unnecessary.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
LeagueCollection leagueCollection = new LeagueCollection() {
leagues = new Leagues() {
League = new List<League>() {
new League() {
Id = 1,
Name = "English Premier League",
Country = "England",
Historical_Data = "Yes",
Fixtures = "Yes",
Livescore = "Yes",
NumberOfMatches = 5700,
LatestMatch = DateTime.Parse( "2015-05-24T16:00:00+00:00")
},
new League() {
Id = 2,
Name = "English League Championship",
Country = "England",
Historical_Data = "Yes",
Fixtures = "Yes",
Livescore = "Yes",
NumberOfMatches = 5700,
LatestMatch = DateTime.Parse("2015-05-24T16:00:00+00:00")
}
}
},
AccountInformation = "Confidential info"
};
XmlSerializer serializer = new XmlSerializer(typeof(LeagueCollection));
StreamWriter writer = new StreamWriter(FILENAME);
serializer.Serialize(writer, leagueCollection);
writer.Flush();
writer.Close();
writer.Dispose();
XmlSerializer deserializer = new XmlSerializer(typeof(LeagueCollection));
XmlTextReader reader = new XmlTextReader(FILENAME);
LeagueCollection XmlData = (LeagueCollection)deserializer.Deserialize(reader);
reader.Close();
}
}
[XmlRoot(ElementName = "LeaugeCollection")]
public class LeagueCollection
{
[XmlElement("Leagues")]
public Leagues leagues { get; set; }
[XmlElement(ElementName = "AccountInformation")]
public string AccountInformation { get; set; }
}
[XmlRoot("Leagues")]
public class Leagues
{
[XmlElement("League")]
public List<League> League { get; set; }
}
[XmlRoot("League")]
public class League
{
[XmlElement(ElementName = "Id")]
public int Id { get; set; }
[XmlElement(ElementName = "Name")]
public string Name { get; set; }
[XmlElement(ElementName = "Country")]
public string Country { get; set; }
[XmlElement(ElementName = "Historical_Data")]
public string Historical_Data { get; set; }
[XmlElement(ElementName = "Fixtures")]
public string Fixtures { get; set; }
[XmlElement(ElementName = "LiveScore")]
public string Livescore { get; set; }
[XmlElement(ElementName = "NumberOfMatches")]
public int NumberOfMatches { get; set; }
[XmlElement(ElementName = "LatestMatch")]
public DateTime LatestMatch { get; set; }
}
}