XML File convert to C# object - c#

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

Related

Retrieve XML column from DataBase with lines C#

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
{
}
}

How to make xmlroot a specific attribute in C#

I recently have change my program to deserialize XML files. I created a class but it needs to be under certain attribute. I thought using XmlRootAttribute would work but I keep getting the error
InvalidOperationException: <DataFileSetup xmlns=''> was not expected.
Here is my code
[XmlRoot(ElementName = "DewesoftSetup")]
public class DewesoftDevices
{
[XmlElement(ElementName = "Devices")]
public List<DewesoftSetup> dewesoftSiriusSetups { get; set; }
};
public class DewesoftSetup
{
public double StartStoreTime;
public int SampleRate;
public int BlockSize;
public int IBRate;
public int AAFsr;
public int MaxSampling;
[XmlElement(ElementName = "Device")]
public List<DeviceType> deviceType { get; set; }
};
public class DeviceType
{
[XmlAttribute(AttributeName = "Type")]
public string deviceType;
[XmlElement(ElementName = "Slot")]
public List<Slot> slot { get; set; }
};
public class Slot
{
public string MeasuredValue { get; set; }
public string Range { get; set; }
public string LPFilter_Type { get; set; }
public string LPFilter_Hz { get; set; }
public string LPFilter_Order { get; set; }
public string HPFilter_Hz { get; set; }
public double AmplScale { get; set; }
public double AmplOffset { get; set; }
public string AmplShortInfo { get; set; }
public string NamePrefix { get; set; }
[XmlElement(ElementName = "OutputChannel")]
public OutputChannel outputChannel;
[XmlElement(ElementName = "AmplifierChainInfo/AmplifierInfo")]
public AmplifierInfo ampInfo;
}
public class DewesoftCard
{
public static string xmlFileName = #"C:\Dewesoft\SetupFile.xml";
public double startStoreTime;
public int sampleRate;
public int blockSize;
public int ibRate;
public int aafSR;
public int maxSampling;
public int startZoomTime;
public int endZoomTime;
};
public class OutputChannel
{
public string Name { get; set; }
public string Description { get; set; }
public string Unit { get; set; }
public int userScaleMin { get; set; }
public int userScaleMax { get; set; }
public int defaultComplexPresent { get; set; }
public string Used { get; set; }
public string Index { get; set; }
public int DataType { get; set; }
public double Scale { get; set; }
public double Offset { get; set; }
public double RangeMax { get; set; }
public double RangeMin { get; set; }
public int BitsLog { get; set; }
public int SigBitCount { get; set; }
public int BitsForMinMax { get; set; }
public int BitCount { get; set; }
public int ExportOrder { get; set; }
public string MeasuredQuantity { get; set; }
public int AmplifierScaleMin { get; set; }
public int AmplifierScaleMax { get; set; }
};
public class AmplifierInfo
{
public string Name { get; set; }
public string Type { get; set; }
public string SerialNr { get; set; }
public string Revision { get; set; }
public string Firmware { get; set; }
public string CalDate { get; set; }
public string Range { get; set; }
public string LP_filter { get; set; }
public string LP_filter_type { get; set; }
public string LP_filter_order { get; set; }
public string HP_filter { get; set; }
};
public static void readXML()
{
XmlReader reader = XmlReader.Create(DewesoftCard.xmlFileName);
reader.ReadToFollowing("DewesoftSetup");
XmlSerializer serializer = new XmlSerializer(typeof(DewesoftDevices));
DewesoftDevices setup = (DewesoftDevices)serializer.Deserialize(reader);
}
<?xml version="1.0" encoding="UTF-8"?>
<DataFileSetup>
<System Name="Local">
<SysInfo>
<Software>
<VersionCreated>X3 SP5 (RELEASE-181228) (64-bit)</VersionCreated>
<VersionModifed>X3 SP5 (RELEASE-181228) (64-bit)</VersionModifed>
<License_Type>Professional</License_Type>
</Software>
</SysInfo>
<DewesoftSetup>
<Devices>
<StartStoreTime>43874.6969328704</StartStoreTime>
<SampleRate>50000</SampleRate>
<BlockSize>1000</BlockSize>
<IBRate>10</IBRate>
<AAFsr>21000</AAFsr>
<MaxSampling>200000</MaxSampling>
<Device Type="AI">
<Slot Index="0">
<MeasuredValue>VOLTAGE</MeasuredValue>
<Range>10 V</Range>
<LPFilter_Type>BU</LPFilter_Type>
<LPFilter_Hz>10000</LPFilter_Hz>
<LPFilter_Order>2</LPFilter_Order>
<HPFilter_Hz>1</HPFilter_Hz>
<OutMathChEnabled>8;1;0;0;0;0;0;0;0</OutMathChEnabled>
<OutputChannel>
<DisplayColor>#FFFF00</DisplayColor>
<Name>ACC-1X</Name>
<Description>Dome</Description>
<DefaultUnit>False</DefaultUnit>
<Unit>g</Unit>
<DefaultComplexPresent>1</DefaultComplexPresent>
<Used>True</Used>
<Index>AI;0</Index>
<DataType>4</DataType>
<Scale>200</Scale>
<RangeMax>2000</RangeMax>
<RangeMin>-2000</RangeMin>
<BitsLog>24</BitsLog>
<SigBitCount>19</SigBitCount>
<BitsForMinMax>24</BitsForMinMax>
<BitCount>24</BitCount>
<SIUnit>
<Label>g</Label>
<PhysicalQuantity>ACCELERATION</PhysicalQuantity>
<MetricPos>1</MetricPos>
<ImperialPos>1</ImperialPos>
<CustomPos>1</CustomPos>
<EditEnable>False</EditEnable>
<Scale>0.101972</Scale>
</SIUnit>
<MeasuredQuantity>ACCELERATION</MeasuredQuantity>
<OnlineInfo>
<IBStream Level="0"></IBStream>
<IBStream Level="1"></IBStream>
<IBStream Level="2"></IBStream>
<IBStream Level="3"></IBStream>
<IBStream Level="4"></IBStream>
<IBStream Level="5"></IBStream>
</OnlineInfo>
<AmplifierScaleMin>-10</AmplifierScaleMin>
<AmplifierScaleMax>10</AmplifierScaleMax>
</OutputChannel>
<AmplifierChainInfo>
<AmplifierInfo Index="0" Type="DEWEUSB_AMPLIFIER">
<Name>SIRIUS-HD-ACC</Name>
<SerialNr>D013C47522</SerialNr>
<Revision>1.3.0.0</Revision>
<Firmware>1.10</Firmware>
<CalDate>09.01.2020</CalDate>
<Measurement>Voltage</Measurement>
<Range>10 V</Range>
<LP_filter>10 kHz* (HW: 100 kHz)</LP_filter>
<LP_filter_type>Butterworth*</LP_filter_type>
<LP_filter_order>2nd*</LP_filter_order>
<HP_filter>AC 1 Hz (SW: 0.1 Hz)</HP_filter>
</AmplifierInfo>
</AmplifierChainInfo>
</Slot>
</Device>
</Devices>
</DewesoftSetup>
</System>
</DataFileSetup>
There are multiple "Device" attributes but I need the one under DewesoftSetup.
EDIT i have added more of the xml document. I am trying to add the device type to a list and the slot to list since there will be multiples of them.
Try following :
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)
{
readXML();
}
public static void readXML()
{
XmlReader reader = XmlReader.Create(FILENAME);
reader.ReadToFollowing("DewesoftSetup");
XmlSerializer serializer = new XmlSerializer(typeof(DewesoftDevices));
DewesoftDevices setup = (DewesoftDevices)serializer.Deserialize(reader);
}
}
[XmlRoot(ElementName = "DewesoftSetup")]
public class DewesoftDevices
{
[XmlElement(ElementName = "Devices")]
public List<Devices> devices { get; set; }
}
public class Devices
{
public string StartStoreTime;
public int SampleRate;
public int IBRate;
public int AAFsr;
public int MaxSampling;
[XmlElement(ElementName = "Device")]
public List<DeviceType> deviceType { get; set; }
}
public class DeviceType
{
[XmlAttribute(AttributeName = "Type")]
public string deviceType;
[XmlElement(ElementName = "Slot")]
public List<Slot> slot { get; set; }
}
public class Slot
{
public string Range { get; set; }
public OutputChannel OutputChannel { get; set; }
[XmlArray("AmplifierChainInfo")]
[XmlArrayItem("AmplifierInfo")]
public List<AmplifierInfo> AmplifierInfo { get; set; }
}
public class OutputChannel
{
public string Name { get; set; }
}
public class AmplifierInfo
{
public string Name { get; set; }
}
}

How to Deserialize XML document?

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; }
}

Xml deserialization returns empty array even though POCO has right xml attributes generated from xsd2code++ tool

I am using XSD2Code++ 2019 tool for visual studio to generate POCOs from aset of 5 xsds. I have added the POCO class below. I see that it has the right xml decorators for it to serialize properly. But I really fail to understand or figure out why the 3rd level object in the returned deserialized data is always empty and not typecasted to the correct type.
I have tried changing attributes to xmlArray and xmlArrayElement too but none of that worked.
POCO class-
https://gist.github.com/nimisha84/b86a4bb2bf37aea6ec351a9f6e331bed
Sample xml response which has null values after deserialization using c# code-
<?xml version="1.0" encoding="UTF-8"?>
<IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2019-07-05T14:29:08.603-07:00">
<QueryResponse startPosition="1" maxResults="1" totalCount="1">
<Invoice domain="QBO" sparse="false">
<Id>8633</Id>
<SyncToken>14</SyncToken>
<MetaData>
<CreateTime>2019-01-09T11:32:12-08:00</CreateTime>
<LastUpdatedTime>2019-06-05T12:49:40-07:00</LastUpdatedTime>
</MetaData>
<CustomField>
<DefinitionId>1</DefinitionId>
<Name>CustomPO</Name>
<Type>StringType</Type>
<StringValue>Gold</StringValue>
</CustomField>
<DocNumber>2830</DocNumber>
<TxnDate>2019-01-09</TxnDate>
<CurrencyRef name="United States Dollar">USD</CurrencyRef>
<ExchangeRate>1</ExchangeRate>
<PrivateNote>Voided - Voided</PrivateNote>
<Line>
<Id>1</Id>
<LineNum>1</LineNum>
<Description>Description</Description>
<Amount>0</Amount>
<DetailType>SalesItemLineDetail</DetailType>
<SalesItemLineDetail>
<ItemRef name="Name27140">815</ItemRef>
<Qty>0</Qty>
<TaxCodeRef>NON</TaxCodeRef>
</SalesItemLineDetail>
</Line>
<Line>
<Amount>0</Amount>
<DetailType>SubTotalLineDetail</DetailType>
<SubTotalLineDetail />
</Line>
<TxnTaxDetail>
<TotalTax>0</TotalTax>
</TxnTaxDetail>
<CustomerRef name="a4">2561</CustomerRef>
<DueDate>2019-01-09</DueDate>
<TotalAmt>0</TotalAmt>
<HomeTotalAmt>0</HomeTotalAmt>
<ApplyTaxAfterDiscount>false</ApplyTaxAfterDiscount>
<PrintStatus>NeedToPrint</PrintStatus>
<EmailStatus>NotSet</EmailStatus>
<Balance>0</Balance>
<Deposit>0</Deposit>
<AllowIPNPayment>false</AllowIPNPayment>
<AllowOnlinePayment>false</AllowOnlinePayment>
<AllowOnlineCreditCardPayment>false</AllowOnlineCreditCardPayment>
<AllowOnlineACHPayment>false</AllowOnlineACHPayment>
</Invoice>
</QueryResponse>
</IntuitResponse>
Code to deserialize-
string responseText = apiResponse.ReadToEnd();
var responseSerializer = new XmlObjectSerializer();
IntuitResponse restResponse =
(IntuitResponse)this.responseSerializer.Deserialize<IntuitResponse>(responseText);
res=restResponse.Items[0] as QueryResponse;
here QueryResponse is not having Invoice(of type IntuitEntity) object returned. Instead empty value is returned. See screenshot.
https://imgur.com/a/5yF6Khb
I really need help to figure out why the 3rd level property is returned as empty.
I tested code below and it works. I manually generated the classes which produces simpler results than using tools.
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)
{
string responseText = File.ReadAllText(FILENAME);
StringReader reader = new StringReader(responseText);
XmlReader xReader = XmlReader.Create(reader);
XmlSerializer serializer = new XmlSerializer(typeof(IntuitResponse));
IntuitResponse response = (IntuitResponse)serializer.Deserialize(xReader);
}
}
[XmlRoot(ElementName = "IntuitResponse", Namespace = "http://schema.intuit.com/finance/v3")]
public class IntuitResponse
{
[XmlAttribute("time")]
public DateTime time { get; set; }
[XmlElement(ElementName = "QueryResponse", Namespace = "http://schema.intuit.com/finance/v3")]
public QueryResponse response { get; set; }
}
public class QueryResponse
{
[XmlAttribute("startPosition")]
public int startPosition { get; set; }
[XmlAttribute("maxResults")]
public int maxResults { get; set; }
[XmlAttribute("totalCount")]
public int totalCount { get; set; }
[XmlElement(ElementName = "Invoice", Namespace = "http://schema.intuit.com/finance/v3")]
public Invoice invoice { get; set; }
}
public class Invoice
{
[XmlAttribute("domain")]
public string domain { get; set; }
[XmlAttribute("sparse")]
public Boolean sparse { get; set; }
public int Id { get; set; }
public int SyncToken { get; set; }
[XmlElement(ElementName = "MetaData", Namespace = "http://schema.intuit.com/finance/v3")]
public MetaData metaData { get; set; }
[XmlElement(ElementName = "CustomField", Namespace = "http://schema.intuit.com/finance/v3")]
public CustomField customField { get; set; }
public int DocNumber { get; set; }
public DateTime TxnDate { get; set; }
[XmlElement(ElementName = "CurrencyRef", Namespace = "http://schema.intuit.com/finance/v3")]
public CurrencyRef currencyRef { get; set; }
public int ExchangeRate { get; set; }
public string PrivateNote { get; set; }
[XmlElement(ElementName = "Line", Namespace = "http://schema.intuit.com/finance/v3")]
public List<Line> line { get; set; }
[XmlElement(ElementName = "TxnTaxDetail", Namespace = "http://schema.intuit.com/finance/v3")]
public TxnTaxDetail txnTaxDetail { get; set; }
[XmlElement(ElementName = "CustomerRef", Namespace = "http://schema.intuit.com/finance/v3")]
public CustomerRef CustomerRef { get; set; }
public DateTime DueDate { get; set; }
public int TotalAmt { get; set; }
public int HomeTotalAmt { get; set; }
public Boolean ApplyTaxAfterDiscount { get; set; }
public string PrintStatus { get; set; }
public string EmailStatus { get; set; }
public int Balance { get; set; }
public int Deposit { get; set; }
public Boolean AllowIPNPayment { get; set; }
public Boolean AllowOnlinePayment { get; set; }
public Boolean AllowOnlineCreditCardPayment { get; set; }
public Boolean AllowOnlineACHPayment { get; set; }
}
public class MetaData
{
public DateTime CreateTime { get; set; }
public DateTime LastUpdatedTime { get; set; }
}
public class CustomField
{
public int DefinitionId { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public string StringValue { get; set; }
}
public class CurrencyRef
{
[XmlAttribute("name")]
public string name { get; set; }
[XmlText]
public string value { get; set; }
}
public class Line
{
public int Id { get; set; }
public int LineNum { get; set; }
public string Description { get; set; }
public decimal Amount { get; set; }
public string DetailType { get; set; }
[XmlElement(ElementName = "SalesItemLineDetail", Namespace = "http://schema.intuit.com/finance/v3")]
public SalesItemLineDetail salesItemLineDetail { get; set; }
}
public class CustomerRef
{
[XmlAttribute("name")]
public string name { get; set; }
[XmlText]
public string value { get; set; }
}
public class SalesItemLineDetail
{
[XmlElement(ElementName = "ItemRef", Namespace = "http://schema.intuit.com/finance/v3")]
public ItemRef itemRef { get; set; }
public int Qty { get; set; }
public string TaxCodeRef { get; set; }
}
public class ItemRef
{
[XmlAttribute("name")]
public string name { get; set; }
[XmlText]
public string value { get; set; }
}
public class TxnTaxDetail
{
public int TotalTax { get; set; }
}
}

XMLSerializer: <ImplementationException xmlns='urn:epcglobal:ale:wsdl:1'> was not expected

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; }
}
}

Categories