Retrieve XML column from DataBase with lines C# - 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
{
}
}

Related

Error deserializing XML file into C# class of objects

I have this xml file:
<?xml version="1.0" encoding="UTF-8"?>
<pippo:Response xmlns:pippo="http://pippoonboarding.eu">
<pippo:Header>
<pippo:FileId>123</pippo:FileId>
<pippo:SenderId>1234</pippo:SenderId>
<pippo:ProcessingDate>20210630</pippo:ProcessingDate>
<pippo:ProcessingTime>1130</pippo:ProcessingTime>
<pippo:ResponseCode>OK</pippo:ResponseCode>
</pippo:Header>
<pippo:CompanyResponse>
<pippo:SellerId>1234</pippo:SellerId>
<pippo:SellerContractCode />
<pippo:VATNumber>123456</pippo:VATNumber>
<pippo:ResponseCode>KO</pippo:ResponseCode>
<pippo:PippoCompanyCode />
<pippo:ResponseDetails>
<pippo:Entity>ciaone</pippo:Entity>
<pippo:ProgressiveNumber>1</pippo:ProgressiveNumber>
<pippo:PippoShopCode />
<pippo:TerminalId />
<pippo:FieldName />
<pippo:ErrorType>DDD</pippo:ErrorType>
<pippo:ErrorCode>1234</pippo:ErrorCode>
<pippo:ErrorDescription>test</pippo:ErrorDescription>
</pippo:ResponseDetails>
</pippo:CompanyResponse>
</pippo:Response>
and I want to deserialize into my class:
public class XmlDeserializer
{
[Serializable, XmlRoot("pippo:Response xmlns:pippo=\"http://pippoonboarding.eu\"")]
public class Root
{
public string Response { get; set; }
//[XmlElement(ElementName = "Header")]
public Header Header { get; set; }
public CompanyResponse CompanyResponse { get; set; }
}
public class Header
{
public string FileId { get; set; }
public string SenderId { get; set; }
public string ProcessingDate { get; set; }
public string ProcessingTime { get; set; }
public string ResponseCode { get; set; }
}
public class CompanyResponse
{
public string SellerId { get; set; }
public int SellerContractCode { get; set; }
public int VATNumber { get; set; }
public int ResponseCode { get; set; }
public int PippoCompanyCode { get; set; }
public ResponseDetails ResponseDetails { get; set; }
}
public class ResponseDetails
{
public string Entity { get; set; }
public string ProgressiveNumber { get; set; }
public string PippoShopCode { get; set; }
public string TerminalId { get; set; }
public string FieldName { get; set; }
public string ErrorType { get; set; }
public string ErrorCode { get; set; }
public string ErrorDescription { get; set; }
}
}
but I receive this error:
There is an error in XML document (2, 2).
<Response xmlns='http://pippoonboarding.eu'> was not expected.
What does the error mean? What should I do?
Following code works. Had to change a few integers to strings in class definitions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication2
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlDeserializer response = new XmlDeserializer(FILENAME);
}
}
public class XmlDeserializer
{
public XmlDeserializer(string filename)
{
XmlReader reader = XmlReader.Create(filename);
XmlSerializer serializer = new XmlSerializer(typeof(Root));
Root response = (Root)serializer.Deserialize(reader);
}
[XmlRoot(ElementName = "Response", Namespace = "http://pippoonboarding.eu")]
public class Root
{
public string Response { get; set; }
//[XmlElement(ElementName = "Header")]
public Header Header { get; set; }
public CompanyResponse CompanyResponse { get; set; }
}
public class Header
{
public string FileId { get; set; }
public string SenderId { get; set; }
public string ProcessingDate { get; set; }
public string ProcessingTime { get; set; }
public string ResponseCode { get; set; }
}
public class CompanyResponse
{
public string SellerId { get; set; }
public string SellerContractCode { get; set; }
public int VATNumber { get; set; }
public string ResponseCode { get; set; }
public string PippoCompanyCode { get; set; }
public ResponseDetails ResponseDetails { get; set; }
}
public class ResponseDetails
{
public string Entity { get; set; }
public string ProgressiveNumber { get; set; }
public string PippoShopCode { get; set; }
public string TerminalId { get; set; }
public string FieldName { get; set; }
public string ErrorType { get; set; }
public string ErrorCode { get; set; }
public string ErrorDescription { 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; }
}
}

XML File convert to C# object

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

Can not deserialize Xml getting from api

I am using World Weather Online API to get the weathers of specific location. My problem is while I am trying to deserialize XML output coming from API Response stream, I am getting error with: There is a problem with XML document (1,1).
Uri apiURL = new Uri(#"http://api.worldweatheronline.com/free/v1/weather.ashx?q=Dhaka&format=xml&num_of_days=1&date=today&key=jzb88bpzb5yvaegukmq97mee");
Stream result = RequestHandler.Process(apiURL.ToString());
XmlSerializer des = new XmlSerializer(typeof(LocalWeather));
StreamReader tr = new StreamReader(result);
Object obj = des.Deserialize(tr);
LocalWeather data = (LocalWeather)obj;
Sample XML file from Web API:
<?xml version="1.0" encoding="UTF-8"?>
<data>
<request>
<type>City</type>
<query>Dhaka, Bangladesh</query>
</request>
<current_condition>
<observation_time>01:57 PM</observation_time>
<temp_C>33</temp_C>
<temp_F>91</temp_F>
<weatherCode>113</weatherCode>
<weatherIconUrl>
<![CDATA[http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0008_clear_sky_night.png]]>
</weatherIconUrl>
<weatherDesc>
<![CDATA[Clear ]]>
</weatherDesc>
<windspeedMiles>2</windspeedMiles>
<windspeedKmph>4</windspeedKmph>
<winddirDegree>77</winddirDegree>
<winddir16Point>ENE</winddir16Point>
<precipMM>0.0</precipMM>
<humidity>76</humidity>
<visibility>10</visibility>
<pressure>1006</pressure>
<cloudcover>2</cloudcover>
</current_condition>
<weather>
<date>2013-10-11</date>
<tempMaxC>36</tempMaxC>
<tempMaxF>97</tempMaxF>
<tempMinC>25</tempMinC>
<tempMinF>77</tempMinF>
<windspeedMiles>5</windspeedMiles>
<windspeedKmph>8</windspeedKmph>
<winddirection>ENE</winddirection>
<winddir16Point>ENE</winddir16Point>
<winddirDegree>65</winddirDegree>
<weatherCode>113</weatherCode>
<weatherIconUrl>
<![CDATA[http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0001_sunny.png]]>
</weatherIconUrl>
<weatherDesc>
<![CDATA[Sunny]]>
</weatherDesc>
<precipMM>0.0</precipMM>
</weather>
</data>
LocalWeather class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace APISample
{
public class LocalWeather
{
public Data data { get; set; }
}
public class Data
{
public List<Current_Condition> current_Condition { get; set; }
public List<Request> request { get; set; }
public List<Weather> weather { get; set; }
}
public class Current_Condition
{
public DateTime observation_time { get; set; }
public DateTime localObsDateTime { get; set; }
public int temp_C { get; set; }
public int windspeedMiles { get; set; }
public int windspeedKmph { get; set; }
public int winddirDegree { get; set; }
public string winddir16Point { get; set; }
public string weatherCode { get; set; }
public List<WeatherDesc> weatherDesc { get; set; }
public List<WeatherIconUrl> weatherIconUrl { get; set; }
public float precipMM { get; set; }
public float humidity { get; set; }
public int visibility { get; set; }
public int pressure { get; set; }
public int cloudcover { get; set; }
}
public class Request
{
public string query { get; set; }
public string type { get; set; }
}
public class Weather
{
public DateTime date { get; set; }
public int tempMaxC { get; set; }
public int tempMaxF { get; set; }
public int tempMinC { get; set; }
public int tempMinF { get; set; }
public int windspeedMiles { get; set; }
public int windspeedKmph { get; set; }
public int winddirDegree { get; set; }
public string winddir16Point { get; set; }
public string weatherCode { get; set; }
public List<WeatherDesc> weatherDesc { get; set; }
public List<WeatherIconUrl> weatherIconUrl { get; set; }
public float precipMM { get; set; }
}
public class WeatherDesc
{
public string value { get; set; }
}
public class WeatherIconUrl
{
public string value { get; set; }
}
}
You need to update the class to match the schema of the XML structure (these are case sensitive).
You can start with your existing file using the attributes found in System.Xml.Serialization.
[XmlRoot("data")]
public class Data {
// and so on..
}
Or you could use the XSD tool to generate the class for you following these steps.
Create schema for the XML returns from the service (Xml -> Create Schema)
In VS Studio tools run this command: XSD XmlSchema.xsd /c (where XmlSchema.xsd is the schema produced in step 1).
The way that your model is set up right now, you have LocalWeather as the root, whereas in the actual XML the root is Data. That's why you're getting the "Invalid root node" error. So, instead of
XmlSerializer des = new XmlSerializer(typeof(LocalWeather));
StreamReader tr = new StreamReader(result);
Object obj = des.Deserialize(tr);
LocalWeather data = (LocalWeather)obj;
try
XmlSerializer des = new XmlSerializer(typeof(Data));
StreamReader tr = new StreamReader(result);
Object obj = des.Deserialize(tr);
Data data = (Data)obj;

Categories