How to Deserialize XML document
My XML
<Title>
<NAME>ABC</NAME>
<BODY>
<A>IAG4</A>
<B>
<B1>
<C>100</C>
<C>EC0001</C1>
<C2>DEF</C2>
<C3>100</C3>
<C4>200</C4>
<C5>600</C5>
<C6>1000</C6>
</B1>
<B1>
<D>101</D>
<D1>EC0002</D1>
</B1>
</B>
</BODY>
</Title>
I want to deserialize this into a class and I want to access them with the objects of the class created. I am using C#.
Use xml serialization code as shown 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(Message));
Message message = (Message)serializer.Deserialize(reader);
}
}
[XmlRoot("MESSAGE")]
public class Message
{
[XmlElement("NAME")]
public string name { get; set; }
[XmlElement("BODY")]
public Body body { get; set; }
}
public class Body
{
[XmlElement("EQPID")]
public string eqpid { get; set; }
[XmlArray("ECS")]
[XmlArrayItem("EC")]
public List<EC> ec { get; set; }
}
public class EC
{
public int ECID { get; set; }
public string ECNAME { get; set; }
public string ECDEF { get; set; }
public int ECSLL { get; set; }
public int ECSUL { get; set; }
public int ECWLL { get; set; }
public int ECWUL { get; set; }
}
}
You could use online tools like Xml2Csharp to generate classes needed to store your XML Data. To deserialize the Xml, you could then use the XmlSerializer
XmlSerializer serializer = new XmlSerializer(typeof(MESSAGE));
using (TextReader reader = new StringReader(xml))
{
var result = (MESSAGE)serializer.Deserialize(reader);
}
Where your classes are defined as
[XmlRoot(ElementName="EC")]
public class EC
{
[XmlElement(ElementName="ECID")]
public string ECID { get; set; }
[XmlElement(ElementName="ECNAME")]
public string ECNAME { get; set; }
[XmlElement(ElementName="ECDEF")]
public string ECDEF { get; set; }
[XmlElement(ElementName="ECSLL")]
public string ECSLL { get; set; }
[XmlElement(ElementName="ECSUL")]
public string ECSUL { get; set; }
[XmlElement(ElementName="ECWLL")]
public string ECWLL { get; set; }
[XmlElement(ElementName="ECWUL")]
public string ECWUL { get; set; }
}
[XmlRoot(ElementName="ECS")]
public class ECS
{
[XmlElement(ElementName="EC")]
public List<EC> EC { get; set; }
}
[XmlRoot(ElementName="BODY")]
public class BODY
{
[XmlElement(ElementName="EQPID")]
public string EQPID { get; set; }
[XmlElement(ElementName="ECS")]
public ECS ECS { get; set; }
}
[XmlRoot(ElementName="MESSAGE")]
public class MESSAGE
{
[XmlElement(ElementName="NAME")]
public string NAME { get; set; }
[XmlElement(ElementName="BODY")]
public BODY BODY { get; set; }
}
Related
I run query against DB which returns me 1 row 2 columns. Each column has XML(script) inside which I need to retrieve into (ideally string) and then execute against DB.
I need the retrieved string to have lines and formatting as if i would copy if from SQL management studio.
Part of XMLresult from SQL management studio I need this format. replacement: XXXXXX
<message>
<header>
<meta version="02" type="OrMessageUdalost_Int" />
<sender name="XXXXXX" appid="XXXXXX" netid="XXXXXX" />
<receiver name="XXXXXX" appid="XXXXXX" netid="XXXXXX" />
<timestamp date="XXXXXX" time="10:11:00" gmt="+XXXXXX" />
<options priority="4" props="XXXXXX" limit="100" />
</header>
<content>
<q1:orMessageUdalost_Int xmlns:q1="XXXXXX" verze="v_2.11">
<hlavicka>
<idDatovaVeta>XXXXXX</idDatovaVeta>
<datumVytvoreni>XXXXXX</datumVytvoreni>
<ciselnikAktualizace>false</ciselnikAktualizace>
<ostrovniRezim>false</ostrovniRezim>
<puvodceDV>
<id>XXXXXX</id>
<kod>XXXXXX</kod>
</puvodceDV>
<idPuvodniDV>XXXXXX</idPuvodniDV>
<puvodniDatumVytvoreni>XXXXXX</puvodniDatumVytvoreni>
<stavUdalosti>XXXXXX</stavUdalosti>
<stavSlozky>
<slozka>
<id>XXXXXX</id>
<kod>XXXXXX</kod>
</slozka>
<isStav>XXXXXX</isStav>
</stavSlozky>
</hlavicka>
<teloFull>
Thanks for any advice.
So the key is to get the proper indentation?
In that case, I would recommend taking a look at the following SO thread:
Format XML string to print friendly XML string
The key is that you need indentation, which can be achieved through the XmlTextWrite.Formatting = Formatting.Indented option.
Use XML serializer. See code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication193
{
class Program
{
const string INPUT_FILENAME = #"c:\temp\test.xml";
const string OUTPUT_FILENAME = #"c:\temp\test1.xml";
static void Main(string[] args)
{
string xml = File.ReadAllText(INPUT_FILENAME);
StringReader sReader = new StringReader(xml);
XmlReader reader = XmlReader.Create(sReader);
XmlSerializer serializer = new XmlSerializer(typeof(Message));
Message message = (Message)serializer.Deserialize(reader);
//write
XmlSerializerNamespaces names = new XmlSerializerNamespaces();
names.Add("q1", "XXXXXX");
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
MemoryStream stream = new MemoryStream();
XmlWriter writer = XmlWriter.Create(stream);
serializer.Serialize(writer,message,names);
byte[] buffer = new byte[stream.Length];
stream.Position = 0;
stream.Read(buffer, 0, (int)stream.Length);
string output = Encoding.UTF8.GetString(buffer);
}
}
[XmlRoot("message")]
public class Message
{
public Header header { get; set; }
public Content content { get; set; }
}
public class Header
{
public Meta meta { get; set; }
public Sender sender { get; set; }
public Receiver receiver { get; set; }
public Timestamp timestamp { get; set; }
public Options options { get; set; }
}
public class Meta
{
[XmlAttribute("version")]
public string version { get; set; }
[XmlAttribute("type")]
public string type { get; set; }
}
public class Sender
{
[XmlAttribute()]
public string name { get; set; }
[XmlAttribute()]
public string appid { get; set; }
[XmlAttribute()]
public string netid { get; set; }
}
public class Receiver
{
[XmlAttribute()]
public string name { get; set; }
[XmlAttribute()]
public string appid { get; set; }
[XmlAttribute()]
public string netid { get; set; }
}
public class Timestamp
{
[XmlAttribute()]
public string date { get; set; }
[XmlAttribute()]
public DateTime timespan { get; set; }
[XmlAttribute()]
public string gmt { get; set; }
}
public class Options
{
[XmlAttribute()]
public int priority { get; set; }
[XmlAttribute()]
public string props { get; set; }
[XmlAttribute()]
public int limit { get; set; }
}
public class Content
{
[XmlElement(Namespace = "XXXXXX")]
public OrMessageUdalost_Int orMessageUdalost_Int { get; set; }
}
public class OrMessageUdalost_Int
{
[XmlAttribute()]
public string verze { get; set; }
[XmlElement(Namespace = "")]
public Hlavicka hlavicka { get; set; }
}
public class Hlavicka
{
public string idDatovaVeta { get; set; }
public string datumVytvoreni { get; set; }
public string ciselnikAktualizace { get; set; }
public Boolean ostrovniRezim { get; set; }
public PuvodceDV puvodceDV { get; set; }
public string idPuvodniDV { get; set; }
public string puvodniDatumVytvoreni { get; set; }
public string stavUdalosti { get; set; }
[XmlArray("stavSlozky")]
[XmlArrayItem("slozka")]
public List<Slozka> slozka { get; set; }
public TeloFull teloFull { get; set; }
}
public class PuvodceDV
{
public string id { get; set; }
public string kod { get; set; }
}
public class Slozka
{
public string id { get; set; }
public string kod { get; set; }
}
public class TeloFull
{
}
}
I am trying to serialize the below XML. But the section "Keys" are not getting populated and its coming as null in the serialized object.
<?xml version="1.0"?>
<Golden>
<SecType>
<ID>New</ID>
<Count>1</Count>
</SecType>
<Request>
<Action>New</Action>
<Keys>
<Key>
<ReferenceType>AAA</ReferenceType>
<ReferenceValue>1111</ReferenceValue>
<Description></Description>
</Key>
<Key>
<ReferenceType>BBBB</ReferenceType>
<ReferenceValue>22222</ReferenceValue>
<Description></Description>
</Key>
</Keys>
</Request></Golden>
I am trying to create a custom class object for further use. Please see my code below.
[Serializable]
[XmlRootAttribute("Golden")]
public class Process
{
[XmlElementAttribute("SecType")]
public SecType secType { get; set; }
[XmlElementAttribute("Request")]
public Request request { get; set; }
}
[Serializable]
[XmlRootAttribute("SecType")]
public class SecType
{
[XmlElementAttribute("ID")]
public string ID { get; set; }
[XmlElementAttribute("Count")]
public int Count { get; set; }
}
[Serializable]
[XmlRootAttribute("Request")]
public class Request
{
[XmlElementAttribute("Action")]
public string Action { get; set; }
[XmlElementAttribute("Keys")]
public Keys keys { get; set; }
}
[Serializable()]
[XmlRootAttribute("Keys")]
public class Keys
{
[XmlArray("Keys")]
[XmlArrayItem("Key", typeof(Key))]
public Key[] key { get; set; }
}
[Serializable]
[XmlRootAttribute("Key")]
public class Key
{
[XmlElementAttribute("ReferenceType")]
public string ReferenceType { get; set; }
[XmlElementAttribute("ReferenceValue")]
public string ReferenceValue { get; set; }
[XmlElementAttribute("Description")]
public string Description { get; set; }
}
string sPath = #"C:\Test\ConsoleApp1\test.xml";
Process proc = new Process();
XmlSerializer serializer = new XmlSerializer(typeof(Process));
StreamReader reader = new StreamReader(sPath);
proc = (Process)serializer.Deserialize(reader);
reader.Close();
I mainly referred this. But it's not working in my implementation.Thanks for you help
I just fixed the Key Element :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication142
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(Process));
Process proc = (Process)serializer.Deserialize(reader);
}
}
[Serializable]
[XmlRootAttribute("Golden")]
public class Process
{
[XmlElementAttribute("SecType")]
public SecType secType { get; set; }
[XmlElementAttribute("Request")]
public Request request { get; set; }
}
[Serializable]
[XmlRootAttribute("SecType")]
public class SecType
{
[XmlElementAttribute("ID")]
public string ID { get; set; }
[XmlElementAttribute("Count")]
public int Count { get; set; }
}
[Serializable]
[XmlRootAttribute("Request")]
public class Request
{
[XmlElementAttribute("Action")]
public string Action { get; set; }
[XmlArray("Keys")]
[XmlArrayItem("Key")]
public Key[] keys { get; set; }
}
[Serializable]
[XmlRootAttribute("Key")]
public class Key
{
[XmlElementAttribute("ReferenceType")]
public string ReferenceType { get; set; }
[XmlElementAttribute("ReferenceValue")]
public string ReferenceValue { get; set; }
[XmlElementAttribute("Description")]
public string Description { get; set; }
}
}
I am trying to serialise a piece of XML that is being returned from a third party API. However when doing so i am only retrieving part of the object upon serialisation. And only some of the values seem to exist. I thought this could be a input type problem, however all the types seem to be correct. I think it may have something to do with how my model is constructed.After debugging the code i have narrowed it down to be a problem with the conversion of the xml into the object.
C# CODE:
//[Route("api/AvailabiliyCheck/GetAvailability/{CSSDistrictCode}/{GoldAddressKey}")]
public EADAvailabilityDetails GetAvailabilityEAD([FromUri] string CSSDistrictCode, [FromUri] string GoldAddressKey)
{
//Load the request xml template
XmlDocument doc = new XmlDocument();
string path = HttpContext.Current.Server.MapPath("~/XML/Availability/GetAvailabilityEAD.xml");
doc.Load(path);
//Assign incoming paramaters to xml template
XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
manager.AddNamespace("stupid_xmlns", "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService");
XmlNode CSSDistrictCodeNode = doc.SelectSingleNode("soap:Envelope/soap:Body/stupid_xmlns:GetAvailability/stupid_xmlns:request/stupid_xmlns:RequestDetails/stupid_xmlns:CSSDistrictCode", manager);
CSSDistrictCodeNode.InnerXml = CSSDistrictCode;
XmlNode GoldAddressKeyNode = doc.SelectSingleNode("soap:Envelope/soap:Body/stupid_xmlns:GetAvailability/stupid_xmlns:request/stupid_xmlns:RequestDetails/stupid_xmlns:GoldAddressKey", manager);
GoldAddressKeyNode.InnerXml = GoldAddressKey;
//Send Request To API
string _url = "https://b2b.api.talktalkgroup.com/api/v2/partners/AvailabilityCheckers/NPAC/v45";
string _action = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService/NetworkProductAvailabilityCheckerService/GetAvailability";
string xml = doc.InnerXml;
var soapResult = WebService.ApiRequest(_url, _action, xml);
XmlDocument xmlToFormat = new XmlDocument();
xmlToFormat.LoadXml(soapResult);
string Outerxml = xmlToFormat.FirstChild.FirstChild.FirstChild.FirstChild.ChildNodes[2].InnerXml;
//Remove all namespaces
var xmlToBeStripped = XElement.Parse(Outerxml);
string finalXml = XmlFormatter.stripNS(xmlToBeStripped).ToString();
EADAvailabilityDetails result;
// Deserialises xlm into an object
XmlSerializer serializer = new XmlSerializer(typeof(EADAvailabilityDetails));
using (TextReader reader = new StringReader(finalXml))
{
result = (EADAvailabilityDetails)serializer.Deserialize(reader);
}
return result;
}
XML being returned:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetAvailabilityResponse xmlns="http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService">
<GetAvailabilityResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Status xmlns="http://schemas.datacontract.org/2004/07/InHouse.SharedLibraries.ServiceBase.BaseTypes">
<Errors/>
<HasErrors>false</HasErrors>
</Status>
<CSSDistrictCode>lv</CSSDistrictCode>
<EADAvailability>
<AvailabilityDetails i:type="EADAvailabilityDetails">
<Status xmlns="http://schemas.datacontract.org/2004/07/InHouse.SharedLibraries.ServiceBase.BaseTypes">
<Errors/>
<HasErrors>false</HasErrors>
</Status>
<EADAvailability>
<EADAvailabilityResult>
<CollectorNodeExchangeCode>NDMAI</CollectorNodeExchangeCode>
<CollectorNodeExchangeName>Maidstone</CollectorNodeExchangeName>
<Distance>0</Distance>
<EADBandwidth xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:string>100M</a:string>
</EADBandwidth>
<EADSubType>EAD-LA</EADSubType>
<FibreExchangeCode>NDACO</FibreExchangeCode>
<FibreExchangename>Archers Court</FibreExchangename>
<IndicativeECC>Within tariff</IndicativeECC>
<IndicativeOrderCategory>Category 2.1</IndicativeOrderCategory>
<LocalExchangeCode>NDACO</LocalExchangeCode>
<LocalExchangeName>Archers Court</LocalExchangeName>
<ORLeadTime>40</ORLeadTime>
<OrderCategoryExplanation>There is a T node within 1km (or 650m in London) with spare capacity and ducting is in place, however some additional cabling is required between the premises and the T node.</OrderCategoryExplanation>
<TTLeadTime>56</TTLeadTime>
<Zone>0</Zone>
</EADAvailabilityResult>
<EADAvailabilityResult>
<CollectorNodeExchangeCode>NDMAI</CollectorNodeExchangeCode>
<CollectorNodeExchangeName>Maidstone</CollectorNodeExchangeName>
<Distance>0</Distance>
<EADBandwidth xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:string>LOW 1GB</a:string>
</EADBandwidth>
<EADSubType>EAD-LA</EADSubType>
<FibreExchangeCode>NDACO</FibreExchangeCode>
<FibreExchangename>Archers Court</FibreExchangename>
<IndicativeECC>Within tariff</IndicativeECC>
<IndicativeOrderCategory>Category 2.1</IndicativeOrderCategory>
<LocalExchangeCode>NDACO</LocalExchangeCode>
<LocalExchangeName>Archers Court</LocalExchangeName>
<ORLeadTime>40</ORLeadTime>
<OrderCategoryExplanation>There is a T node within 1km (or 650m in London) with spare capacity and ducting is in place, however some additional cabling is required between the premises and the T node.</OrderCategoryExplanation>
<TTLeadTime>56</TTLeadTime>
<Zone>0</Zone>
</EADAvailabilityResult>
<EADAvailabilityResult>
<CollectorNodeExchangeCode>NDCAN</CollectorNodeExchangeCode>
<CollectorNodeExchangeName>Canterbury</CollectorNodeExchangeName>
<Distance>20656</Distance>
<EADBandwidth xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:string>HIGH 1GB</a:string>
</EADBandwidth>
<EADSubType>EAD-NonLA</EADSubType>
<FibreExchangeCode>NDCAN</FibreExchangeCode>
<FibreExchangename>Canterbury</FibreExchangename>
<IndicativeECC>Within tariff</IndicativeECC>
<IndicativeOrderCategory>Category 2.1</IndicativeOrderCategory>
<LocalExchangeCode>NDACO</LocalExchangeCode>
<LocalExchangeName>Archers Court</LocalExchangeName>
<ORLeadTime>40</ORLeadTime>
<OrderCategoryExplanation>There is a T node within 1km (or 650m in London) with spare capacity and ducting is in place, however some additional cabling is required between the premises and the T node.</OrderCategoryExplanation>
<TTLeadTime>56</TTLeadTime>
<Zone>B</Zone>
</EADAvailabilityResult>
</EADAvailability>
<LeadTime>10</LeadTime>
</AvailabilityDetails>
</EADAvailability>
<GoldAddressKey>A00009292752</GoldAddressKey>
<Postcode/>
</GetAvailabilityResult>
</GetAvailabilityResponse>
</s:Body>
</s:Envelope>
Model:
[Serializable, XmlRoot("AvailabilityDetails")]
public class EADAvailabilityDetails
{
[XmlElement("EADAvailability")]
public EADAvailability EADAvailability { get; set; }
}
public class EADAvailability
{
[XmlElement("EADAvailabilityResult")]
public List<EADAvailabilityResult> EADAvailabilityResult { get; set; }
}
public class EADAvailabilityResult
{
[XmlElement("CollectorNodeExchangeCode")]
public string CollectorNodeExchangeCode { get; set; }
[XmlElement("CollectorNodeExchangeName")]
public string CollectorNodeExchangeName { get; set; }
[XmlElement("Distance")]
public int Distance { get; set; }
[XmlElement("EADBandwidth")]
public string EADBandwidth { get; set; }
[XmlElement("EADSubType")]
public string EADSubType { get; set; }
[XmlElement("FibreExchangeCode")]
public string FibreExchangeCode { get; set; }
[XmlElement("FibreExchangename")]
public string FibreExchangename { get; set; }
[XmlElement("IndicativeECC")]
public string IndicativeECC { get; set; }
[XmlElement("IndicativeOrderCategory")]
public string IndicativeOrderCategory { get; set; }
[XmlElement("LocalExchangeCode")]
public string LocalExchangeCode { get; set; }
[XmlElement("LocalExchangeName")]
public string LocalExchangeName { get; set; }
[XmlElement("ORLeadTime")]
public int ORLeadTime { get; set; }
[XmlElement("OrderCategoryExplanation")]
public string OrderCategoryExplanation { get; set; }
[XmlElement("TTLeadTime")]
public int TTLeadTime { get; set; }
[XmlElement("Zone")]
public int Zone { get; set; }
}
XML after serialisation:
{
"<EADAvailability>k__BackingField": {
"EADAvailabilityResult": [
{
"CollectorNodeExchangeCode": "NDMAI",
"CollectorNodeExchangeName": "Maidstone",
"Distance": 0,
"EADBandwidth": "100M",
"EADSubType": null,
"FibreExchangeCode": null,
"FibreExchangename": null,
"IndicativeECC": null,
"IndicativeOrderCategory": null,
"LocalExchangeCode": null,
"LocalExchangeName": null,
"ORLeadTime": 0,
"OrderCategoryExplanation": null,
"TTLeadTime": 0,
"Zone": 0
}
]
}
}
The code below works :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication139
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
Envelope envelope = (Envelope)serializer.Deserialize(reader);
}
}
[XmlRoot(Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope
{
[XmlElement (Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public Body Body { get; set; }
}
public class Body
{
[XmlElement(Namespace = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService")]
public GetAvailabilityResponse GetAvailabilityResponse { get; set; }
}
public class GetAvailabilityResponse
{
[XmlElement(Namespace = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService")]
public GetAvailabilityResult GetAvailabilityResult { get; set; }
}
public class GetAvailabilityResult
{
[XmlArray("EADAvailability", Namespace = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService")]
[XmlArrayItem("AvailabilityDetails", Namespace = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService")]
public AvailabilityDetails[] AvailabilityDetails { get; set; }
}
[XmlInclude(typeof(EADAvailabilityDetails))]
[Serializable, XmlRoot("AvailabilityDetails", Namespace = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService")]
public class AvailabilityDetails
{
}
[Serializable, XmlRoot("EADAvailabilityDetails", Namespace = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService")]
public class EADAvailabilityDetails : AvailabilityDetails
{
[XmlArray("EADAvailability", Namespace = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService")]
[XmlArrayItem("EADAvailabilityResult", Namespace = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService")]
public EADAvailabilityResult[] EADAvailabilityResult { get; set; }
}
public class EADAvailabilityResult
{
public string CollectorNodeExchangeCode { get; set; }
public string CollectorNodeExchangeName { get; set; }
public int Distance { get; set; }
public EADBandwidth EADBandwidth { get; set; }
public string EADSubType { get; set; }
public string FibreExchangeCode { get; set; }
public string FibreExchangename { get; set; }
public string IndicativeECC { get; set; }
public string IndicativeOrderCategory { get; set; }
public string LocalExchangeCode { get; set; }
public string LocalExchangeName { get; set; }
public int ORLeadTime { get; set; }
public string OrderCategoryExplanation { get; set; }
public int TTLeadTime { get; set; }
public string Zone { get; set; }
}
public class EADBandwidth
{
[XmlElement(ElementName = "string", Type = typeof(string), Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")]
public string String { get; set; }
}
}
I have to read this XML File in a C# Object. That i have these information in an Object. Not all tags are important!
These would be the important information i need in the Object:
- Alignment with the staStart Property
- CoordGoem with Line Spiral and Curve inside and of thesse are only the properties important
XML File
<Alignments name="">
<Alignment name="AL-voor omvorming landxml" length="6550.000000000015" staStart="30000." desc="">
<CoordGeom>
<Line dir="0." length="100.">
<Start>175.282796686952 -1708.474133524573</Start>
<End>175.282796686952 -1608.474133524573</End>
</Line>
<Spiral length="100." radiusEnd="500." radiusStart="INF" rot="cw" spiType="clothoid" theta="5.729577951308" totalY="3.330953138396" totalX="99.900046285614" tanLong="66.701620764677" tanShort="33.365112106501">
<Start>175.282796686952 -1608.474133524573</Start>
<PI>175.282796686952 -1541.772512759896</PI>
<End>171.951843548555 -1508.574087238959</End>
</Spiral>
<Curve rot="cw" chord="99.833416646828" crvType="arc" delta="11.459155902616" dirEnd="342.811266146075" dirStart="354.270422048692" external="2.510459200228" length="100." midOrd="2.497917360987" radius="500." tangent="50.167336042725">
<Start>171.951843548555 -1508.574087238959</Start>
<Center>-325.550239090457 -1558.490795562373</Center>
<End>152.118005472345 -1410.730692231703</End>
<PI>166.94346698734 -1458.657378915545</PI>
</Curve>
<Spiral length="100." radiusEnd="INF" radiusStart="500." rot="cw" spiType="clothoid" theta="5.729577951308" totalY="3.330953138396" totalX="99.900046285614" tanLong="66.701620764677" tanShort="33.365112106501">
<Start>152.118005472345 -1410.730692231703</Start>
<PI>142.257940647353 -1378.855783172596</PI>
<End>116.283106059873 -1317.419522049479</End>
</Spiral>
Object
public class LandXMLAlignments
{
public long staStart { get; set; }
[XmlArray("CoordGeom")]
public List<LandXMLAlignmentsCoordGeom> CoordGeoms { get; set; }
}
public class LandXMLAlignmentsCoordGeom
{
public List<LandXMLAlignmentsCoordGeomLine> CoordGeomLines { get; set; }
public List<LandXMLAlignmentsCoordGeomSpiral> CoordGeomSpiral { get; set; }
public List<LandXMLAlignmentsCoordGeomLine> CoordGeomCurve { get; set; }
}
[System.Xml.Serialization.XmlType("Line", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomLine
{
public int length { get; set; }
public int position { get; set; }
}
[System.Xml.Serialization.XmlType("Spiral", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomSpiral
{
public int position { get; set; }
public int length { get; set; }
public string radiusStart { get; set; }
public string radiusEnd { get; set; }
public string rot { get; set; }
public string spiType { get; set; }
}
[System.Xml.Serialization.XmlType("Curve", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomCurve
{
public int position { get; set; }
public int length { get; set; }
public int radiusStart { get; set; }
public string rot { get; set; }
}
I would have drawn this object from it but i don't now how i actually read the xml file in this Object.
Assuming your classes are ok you could just create a helper class to perfom transformations from XML to a POCO object like this:
public static class XmlHelper
{
public static T ParseXmlFile<T>(string filePath)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StreamReader(filePath))
{
T configuration = (T)serializer.Deserialize(reader);
return configuration;
}
}
}
And use it like this:
var alignments = XmlHelper.ParseXmlFile<LandXMLAlignments>(YourXMLPath);
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication51
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(Alignments));
Alignments alignments = (Alignments)serializer.Deserialize(reader);
}
}
public class Alignments
{
[XmlElement("Alignment")]
public Alignment alignment { get; set; }
}
public class Alignment
{
public long staStart { get; set; }
[XmlElement("CoordGeom")]
public List<LandXMLAlignmentsCoordGeom> CoordGeoms { get; set; }
}
public class LandXMLAlignmentsCoordGeom
{
[XmlElement("Line")]
public List<LandXMLAlignmentsCoordGeomLine> CoordGeomLines { get; set; }
[XmlElement("Spiral")]
public List<LandXMLAlignmentsCoordGeomSpiral> CoordGeomSpiral { get; set; }
[XmlElement("Curve")]
public List<LandXMLAlignmentsCoordGeomLine> CoordGeomCurve { get; set; }
}
[System.Xml.Serialization.XmlType("Line", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomLine
{
public int length { get; set; }
public int position { get; set; }
}
[System.Xml.Serialization.XmlType("Spiral", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomSpiral
{
public int position { get; set; }
public int length { get; set; }
public string radiusStart { get; set; }
public string radiusEnd { get; set; }
public string rot { get; set; }
public string spiType { get; set; }
}
[System.Xml.Serialization.XmlType("Curve", IncludeInSchema = true)]
public class LandXMLAlignmentsCoordGeomCurve
{
public int position { get; set; }
public int length { get; set; }
public int radiusStart { get; set; }
public string rot { get; set; }
}
}
If you are using Visual studio, then do the following:
Copy XML
Select Edit Menu,
Paste Special, Paste XML as Classes.
Reference
I am trying to deserialize an XML that looks like this:
XML:
<?xml version="1.0" encoding="UTF-8"?>
<ns2:ECReports xmlns:ns2="urn:epcglobal:ale:xsd:1" xmlns:ns3="urn:epcglobal:ale:wsdl:1" specName="Cycle_MDEAirport_1" date="2016-04-25T15:06:19.980Z"
ALEID="RIFIDI-ALE1158647263" totalMilliseconds="9492" terminationCondition="DURATION">
<reports>
<report reportName="Cycle_MDEAirport">
<group>
<groupList>
<member>
<epc>303400c0e4a3f48000a2f8d5</epc>
</member>
</groupList>
</group>
</report>
</reports>
<ECSpec includeSpecInReports="true">
<logicalReaders>
<logicalReader>MDEAirport</logicalReader>
</logicalReaders>
<boundarySpec>
<repeatPeriod unit="MS">10000</repeatPeriod>
<duration unit="MS">9500</duration>
<stableSetInterval unit="MS">0</stableSetInterval>
</boundarySpec>
<reportSpecs>
<reportSpec reportName="Cycle_MDEAirport" reportIfEmpty="true" reportOnlyOnChange="false">
<reportSet set="ADDITIONS" />
<output includeEPC="true" includeTag="true" includeRawHex="true" includeRawDecimal="true" />
</reportSpec>
</reportSpecs>
</ECSpec>
</ns2:ECReports>
But I get the following error:
<ImplementationException xmlns='urn:epcglobal:ale:wsdl:1'> was not expected
Here is my code:
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "ECReports";
xRoot.Namespace = "urn:epcglobal:ale:xsd:1";
xRoot.IsNullable = true;
XmlSerializer serializer = new XmlSerializer(typeof(ECReports), xRoot);
MemoryStream ms = new MemoryStream(e.Message);
ECReports ECReports;
ECReports = (ECReports)serializer.Deserialize(ms);
The class ECReports that I am using is from a Service Reference (it is not a class developed by me)
I found the issue. You are going from a namespace to a non-namespace so you have to specify the namespace as "".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
byte[] message = File.ReadAllBytes(FILENAME);
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "ECReports";
xRoot.Namespace = "urn:epcglobal:ale:xsd:1";
xRoot.IsNullable = true;
XmlSerializer serializer = new XmlSerializer(typeof(ECReports), xRoot);
MemoryStream ms = new MemoryStream(message);
ECReports ECReports;
ECReports = (ECReports)serializer.Deserialize(ms);
}
}
[XmlRoot("ECReports")]
public class ECReports
{
[XmlAttribute("specName")]
public string specName { get; set; }
[XmlAttribute("date")]
public DateTime date { get; set; }
[XmlAttribute("ALEID")]
public string aleid { get; set; }
[XmlAttribute("totalMilliseconds")]
public int totalMilliseconds { get; set; }
[XmlAttribute("terminationCondition")]
public string terminationCondition { get; set; }
[XmlElement(ElementName = "reports", Namespace = "")]
public Reports reports { get; set; }
[XmlElement(ElementName = "ECSpec", Namespace = "")]
public ECSpec ecSpec { get; set; }
}
[XmlRoot(ElementName = "reports", Namespace = "")]
public class Reports
{
[XmlElement("report")]
public Report report { get; set; }
}
[XmlRoot("report")]
public class Report
{
[XmlAttribute("reportName")]
public string reportName { get; set; }
[XmlElement("group")]
public Group group { get; set; }
}
[XmlRoot("group")]
public class Group
{
[XmlElement("groupList")]
public GroupList groupList { get; set; }
}
[XmlRoot("groupList")]
public class GroupList
{
[XmlElement("member")]
public Member member { get; set; }
}
[XmlRoot("member")]
public class Member
{
[XmlElement("epc")]
public string epc { get; set; }
}
[XmlRoot("ECSpec", Namespace = "")]
public class ECSpec
{
[XmlAttribute("includeSpecInReports")]
public Boolean includeSpecInReports { get; set; }
[XmlElement("logicalReaders")]
public LogicalReaders logicalReaders { get; set; }
[XmlElement("boundarySpec")]
public BoundarySpec boundarySpec { get; set; }
[XmlElement("reportSpecs")]
public ReportSpecs reportSpecs { get; set; }
}
[XmlRoot("logicalReaders")]
public class LogicalReaders
{
[XmlElement("logicalReader")]
public string logicalReader { get; set; }
}
[XmlRoot("boundarySpec")]
public class BoundarySpec
{
[XmlElement("repeatPeriod")]
public Unit repeatPeriod { get; set; }
[XmlElement("duration")]
public Unit duration { get; set; }
[XmlElement("stableSetInterval")]
public Unit stableSetInterval { get; set; }
}
[XmlRoot("reportSpecs")]
public class ReportSpecs
{
[XmlElement("reportSpec")]
public ReportSpec reportSpec { get; set; }
}
[XmlRoot("")]
public class Unit
{
[XmlAttribute("unit")]
public string unit { get; set; }
[XmlText]
public int value { get; set; }
}
[XmlRoot("reportSpec")]
public class ReportSpec
{
[XmlAttribute("reportName")]
public string reportName { get; set; }
[XmlAttribute("reportIfEmpty")]
public Boolean reportIfEmpty { get; set; }
[XmlAttribute("reportOnlyOnChange")]
public Boolean reportOnlyOnChange { get; set; }
[XmlElement("reportSet")]
public ReportSet reportSet { get; set; }
[XmlElement("output")]
public Output output { get; set; }
}
[XmlRoot("reportSet")]
public class ReportSet
{
[XmlAttribute("set")]
public string set { get; set; }
}
[XmlRoot("output")]
public class Output
{
[XmlAttribute("includeEPC")]
public Boolean includeEPC { get; set; }
[XmlAttribute("includeTag")]
public Boolean includeTag { get; set; }
[XmlAttribute("includeRawHex")]
public Boolean includeRawHex { get; set; }
[XmlAttribute("includeRawDecimal")]
public Boolean includeRawDecimal { get; set; }
}
}