We're redoing a legacy application using .Net MVC 5. Part of the application generates an XML feed which other applications use.
We've built a model called Call
[XmlRoot("record")]
public class Call
{
[XmlIgnore]
public int ID { get; set; }
[XmlIgnore]
public string CustomerInitials { get; set; }
[XmlIgnore]
public string Prefix { get; set; }
[XmlIgnore]
public string Code { get; set; }
[XmlIgnore]
public string CustomerNumber { get; set; }
[XmlElement("starttime")]
public DateTime Entry { get; set; }
[XmlElement("endtime")]
public DateTime Exit { get; set; }
[XmlElement("cnumber")][NotMapped]
public string Number
{
get { return Prefix + Code + CustomerNumber; }
}
}
With a controller:
public class CallsController : ApiController
{
private DbContext db = new DbContext();
// GET: api/Calls
public IQueryable<Call> GetCalls()
{
return db.Calls;
}
}
Which produces an XML feed of:
<ArrayOfCall xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Call>
<starttime>2016-01-15T14:45:24.447</starttime>
<endtime>2016-01-15T15:45:24.447</endtime>
</Call>
<Call>
<starttime>2016-01-15T15:46:35.637</starttime>
<endtime>2016-01-15T16:46:35.637</endtime>
</Call>
</ArrayOfCall>
However, I need to customize the XML feed to provide the following output:
<?xml version="1.0" encoding="UTF-8"?>
<DATA>
<RECORD>
<CNUMBER>593042401</CNUMBER>
<STARTTIME>2016-01-15T14:45:24.447</STARTTIME>
<ENDTIME>2016-01-15T15:45:24.447</ENDTIME>
</RECORD>
<RECORD>
<CNUMBER>593042401</CNUMBER>
<STARTTIME>2016-01-15T15:46:35.637</STARTTIME>
<ENDTIME>2016-01-15T16:46:35.637</ENDTIME>
</RECORD>
</DATA>
The XmlRoot data annotation is not followed and the CNumber is not included in my XML feed. The calls should display as <record> in the XML feed with the root being <data>. How do I resolve these issues? Am I going about this the wrong way? Should I be using a View Model instead?
1.- The Data class:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace StackOverflow
{
public class Call
{
[XmlIgnore]
public int ID { get; set; }
[XmlIgnore]
public string CustomerInitials { get; set; }
[XmlIgnore]
public string Prefix { get; set; }
[XmlIgnore]
public string Code { get; set; }
[XmlIgnore]
public string CustomerNumber { get; set; }
[XmlElement("CNUMBER")]
public string Number
{
get { return Prefix + Code + CustomerNumber; }
}
[XmlElement("STARTTIME")]
public DateTime Entry { get; set; }
[XmlElement("ENDTIME")]
public DateTime Exit { get; set; }
}
[XmlRoot(ElementName = "DATA")]
public class Data
{
[XmlElement("RECORD")]
public List<Call> Calls;
}
}
2.- Using your example data:
// 1.- Data
var data = new Data();
var calls = new List<Call>
{
new Call
{
Entry = new DateTime(2016, 1, 15, 14, 45, 24, 447),
Exit = new DateTime(2016, 1, 15, 15, 45, 24, 447)
},
new Call
{
Entry = new DateTime(2016, 1, 15, 15, 46, 35, 637),
Exit = new DateTime(2016, 1, 15, 16, 46, 35, 637)
}
};
data.Calls = new List<Call>(calls);
// 2.- Serialize the objet to byte[]
var dataByteArray = new XmlSerializerHelper<Data>().ObjectToByteArray(data, Encoding.GetEncoding("UTF-8"), true);
// 3.- Save the byte[] to disk
File.WriteAllBytes("D:/xml.xml", dataByteArray);
3.- The serializer helper:
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace StackOverflow
{
public class XmlSerializerHelper<T> where T : class
{
private readonly XmlSerializer _serializer;
public XmlSerializerHelper()
{
_serializer = new XmlSerializer(typeof(T));
}
public byte[] ObjectToByteArray(T obj, Encoding encoding = null, bool ignoreNAmespaces = false)
{
var settings = GetSettings(encoding);
using (var memoryStream = new MemoryStream())
{
using (var writer = XmlWriter.Create(memoryStream, settings))
{
if (ignoreNAmespaces)
{
var serializerNamespaces = new XmlSerializerNamespaces();
serializerNamespaces.Add("", "");
_serializer.Serialize(writer, obj, serializerNamespaces);
}
else
{
_serializer.Serialize(writer, obj);
}
}
return memoryStream.ToArray();
}
}
private XmlWriterSettings GetSettings(Encoding encoding)
{
return new XmlWriterSettings
{
Encoding = encoding ?? Encoding.GetEncoding("ISO-8859-1"),
Indent = true,
IndentChars = "\t",
NewLineChars = Environment.NewLine,
ConformanceLevel = ConformanceLevel.Document
};
}
}
}
4.- Output:
<?xml version="1.0" encoding="utf-8"?>
<DATA>
<RECORD>
<STARTTIME>2016-01-15T14:45:24.447</STARTTIME>
<ENDTIME>2016-01-15T15:45:24.447</ENDTIME>
</RECORD>
<RECORD>
<STARTTIME>2016-01-15T15:46:35.637</STARTTIME>
<ENDTIME>2016-01-15T16:46:35.637</ENDTIME>
</RECORD>
</DATA>
Cheers
To create XML that would match the what you are wanting you could create an Object named Data which could provide a list that would hold Records.
public class Data{
public List<Record> Records{get;set;}
}
Currently you are returning an array of Calls.
Related
Let me explain, there is a database table which has 1 XML column named audits and other common types of column.
so is this possible to deserialize below XML into class.
<?xml version="1.0"?>
<entity type="Order">
<id type="System.Int64">146</id>
<ordernumber type="System.String">OD555</ordernumber>
<audits type='System.String'>
<audit>
<item>
<create timestamp='2017-07-19 10:02:13' userid='23' />
</item>
<invoice>
<create timestamp='2017-07-19 10:03:37' userid='45' />
</invoice>
</audit>
</audits>
</entity>
Class:
public class Order
{
public long id { get; set; }
public string ordernumber { get; set; }
public string audits { get; set; }
}
Modifying your model with the attributes XmlType and XmlAnyElement (requires XmlElement as type)
[XmlType("entity")]
public class Order
{
public long id { get; set; }
public string ordernumber { get; set; }
[XmlAnyElement]
public XmlElement audits { get; set; }
}
allows to deserialize the complete XML string like
using (MemoryStream stream = new MemoryStream())
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(xmlString);
writer.Flush();
stream.Position = 0;
XmlSerializer serializer = new XmlSerializer(typeof(Order));
Order o = (Order)serializer.Deserialize(stream);
}
Now you are able to get the audits as string like
string auditsString = o.audits.InnerXml;
You can also add a property to your model to simplify the access:
public string auditsString
{
get
{
return audits.InnerXml;
}
}
Try xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication68
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
Order order = doc.Descendants("entity").Select(x => new Order()
{
id = (long)x.Element("id"),
ordernumber = (string)x.Element("ordernumber"),
audits = x.Descendants("create").Select(y => (DateTime)y.Attribute("timestamp")).ToList()
}).FirstOrDefault();
}
}
public class Order
{
public long id { get; set; }
public string ordernumber { get; set; }
public List<DateTime> audits { get; set; }
}
}
You can try like this
const string xmlString = #"<columns><column><c1>100</c1><c2>200</c2><cn>300</cn></column><column><c1>111</c1><c2>222</c2><cn>333</cn></column> <column> <c1>MAX Newsletter</c1><c2>OLS Application</c2> <cn>Total funded accounts</cn> </column></columns>";
XDocument doc = XDocument.Parse(xmlString);
if (doc.Root != null)
{
List<Row> items = (from r in doc.Root.Elements("column")
select new Row
{
C1 = (string)r.Element ("C1"),
C2 = (string)r.Element("C2"),
}).ToList();
The part at the "invoiceUnit.Items.Add(itemOne);" I get an error. It says:
1. System.NullReferenceException: 'Object reference not set to an
instance of an object.'
2. PROGRAM_B2.Program.Order.Items.get returned null.
Also when I comment out that line of codes, I managed to get it run but the data in invoiceDataOut.xml is nothing. The serializer doesn't seem to be working.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
namespace PROGRAM_B2
{
// This is the class that we want to serialize:.
[Serializable()]
public class Program
{
// Main class which is directly accessed
public class Order
{
public int InvoiceID { get; set; }
private DateTime _InvoiceDate { get; set; }
public string InvoiceDate {
get { return _InvoiceDate.ToString("d/m/yyyy"); }
set { _InvoiceDate = DateTime.ParseExact(value, "d/m/yyyy", CultureInfo.InvariantCulture); }
}
public int SellerID { get; set; }
public int BuyerID { get; set; }
public int OrderID { get; set; }
public List<Item> Items { get; set; }
public double ShippingCharges { get; set; }
public double InvoiceTotalCost { get; set; }
}
// Indirectly accessed class
public class Item
{
public int ItemID { get; set; }
public string ItemName { get; set; }
public string Description { get; set; }
public int Quantity { get; set; }
public double NewUnitPrice { get; set; }
}
static void Main(string[] args)
{
Order invoiceUnit = new Order();
// Simple Type - Main Data
invoiceUnit.InvoiceID = 0011995;
invoiceUnit.InvoiceDate = "12/5/2017";
invoiceUnit.SellerID = 0020;
invoiceUnit.BuyerID = 1231;
invoiceUnit.OrderID = 9021;
// An Item -Multiple
Item itemOne = new Item();
itemOne.ItemID = 0001;
itemOne.ItemName = "Apple Macbook Pro";
itemOne.Description = "The best professional laptop for professionals.";
itemOne.Quantity = 5;
itemOne.NewUnitPrice = 4950.50;
// Add Item
invoiceUnit.Items.Add(itemOne);
// An Item -Multiple
Item itemTwo = new Item();
itemTwo.ItemID = 0002;
itemTwo.ItemName = "Microsoft Surface Laptop";
itemTwo.Description = "The most versatile professional laptop for experts.";
itemTwo.Quantity = 10;
itemTwo.NewUnitPrice = 3500.90;
// Add Item
invoiceUnit.Items.Add(itemTwo);
// Simple Type - Footer Data
invoiceUnit.ShippingCharges = 7000.00;
invoiceUnit.InvoiceTotalCost = 19500.10;
// Create a new XmlSerializer instance with the type of the test class
XmlSerializer SerializerObj = new XmlSerializer(typeof(Program));
// Create a new file stream to write the serialized object to a file
TextWriter WriteFileStream = new StreamWriter(#"../../../invoiceDataOut.xml");
SerializerObj.Serialize(WriteFileStream, invoiceUnit);
// Cleanup
WriteFileStream.Close();
/*
The test.xml file will look like this:
<?xml version="1.0"?>
<TestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SomeString>foo</SomeString>
<Settings>
<string>A</string>
<string>B</string>
<string>C</string>
</Settings>
</TestClass>
*/
// Test the new loaded object:
/*Console.WriteLine(invoiceUnit.someString);
foreach (string Setting in invoiceUnit.Settings)
{
Console.WriteLine(Setting);
}
Console.ReadLine();
*/
}
}
}
Please let me know how I can make it better.
I have the following XML format:-
<?xml version="1.0"?>
<Price xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<amount>
<currency>USD</currency>
100
</amount>
<amount>
<currency>EUR</currency>
50
</amount>
</Price>
the XML value contains the amount in the xml root. May I know how can I serialize the value of 100 & 50 ?
[Serializable]
[XmlRoot("amount")]
public sealed class amount
{
[XmlElement("currency")]
public string currency{ get; set; }
}
class Program
{
static void Main(string[] args)
{
var list = new List<amount> {new amount() {Description = "USD"}, new amount() {Description = "EUR"}};
var serializer = new XmlSerializer(typeof(List<amount>), new XmlRootAttribute("Price"));
var ms = new MemoryStream();
serializer.Serialize(ms, list);
ms.Position = 0;
var result = new StreamReader(ms).ReadToEnd();
}
}
You can use XmlText:
[XmlRoot("amount")]
public sealed class amount
{
[XmlElement("currency")]
public string Description { get; set; }
// http://stackoverflow.com/a/1528429/613130
[XmlIgnore]
public int Value { get; set; }
[XmlText]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public string ValueXml
{
get
{
return XmlConvert.ToString(Value);
}
set
{
Value = XmlConvert.ToInt32(value);
}
}
}
I'm trying to create a XML something like this :
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
- <inventory_report:inventoryReportMessage xmlns:inventory_report="urn:gs1:ecom:inventory_report:xsd:3" xmlns:sh="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader" xmlns:ecom_common="urn:gs1:ecom:ecom_common:xsd:3" xmlns:shared_common="urn:gs1:shared:shared_common:xsd:3">
- <sh:StandardBusinessDocumentHeader>
<sh:HeaderVersion>Standard Business Header version 1.3</sh:HeaderVersion>
- <sh:Sender>
<sh:Identifier Authority="GS1">0000</sh:Identifier>
- <sh:ContactInformation>
<sh:Contact>some one</sh:Contact>
<sh:EmailAddress>someone#example.com</sh:EmailAddress>
<sh:TelephoneNumber>00357</sh:TelephoneNumber>
<sh:ContactTypeIdentifier>IT Support</sh:ContactTypeIdentifier>
</sh:ContactInformation>
</sh:Sender>
I'm using the below code for creating the XML -->
var xelementNode = doc.CreateElement("inventory_report", "inventoryReportMessage","urn:gs1:ecom:inventory_report:xsd:3");
doc.AppendChild(xelementNode);
var xelementSubNode = doc.CreateElement("sh", xelementNode, "StandardBusinessDocumentHeades","");
xelementNode.AppendChild(xelementSubNode);
I'm getting this output for the above code -->
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes" ?>
- <inventory_report:inventoryReportMessage xmlns:inventory_report="urn:gs1:ecom:inventory_report:xsd:3">
- <StandartBusinessDocumentHeader>
<HeaderVersion>Standard Business Header Version 1.3</HeaderVersion>
- <Sender>
<Identifier>GS1</Identifier>
- <ContactInformation>
<Contact>Turkey IT Support</Contact>
<EmailAddress>someone#example.com</EmailAddress>
<TelephoneNumber>00 13</TelephoneNumber>
<ContactTypeIdentifier>IT Support</ContactTypeIdentifier>
</ContactInformation>
</Sender>
</StandartBusinessDocumentHeader>
</inventory_report:inventoryReportMessage>
The second prefix ("sh") doesn't work. Can someone help me???
For serialization approach, you can define classes:
public class ContactInformation
{
[XmlElement(ElementName = "Contact")]
public string Contact { get; set; }
[XmlElement(ElementName = "EmailAddress")]
public string EmailAddress { get; set; }
[XmlElement(ElementName = "TelephoneNumber")]
public string TelephoneNumber { get; set; }
[XmlElement(ElementName = "ContactTypeIdentifier")]
public string ContactTypeIdentifier { get; set; }
}
public class Identifier
{
[XmlAttribute("Authority")]
public string Authority { get; set; }
[XmlText]
public string Value { get; set; }
}
public class Sender
{
[XmlElement(ElementName = "Identifier")]
public Identifier Identifier { get; set; }
[XmlElement(ElementName = "ContactInformation")]
public ContactInformation ContactInformation { get; set; }
}
public class StandartBusinessDocumentHeader
{
[XmlElement(ElementName = "HeaderVersion")]
public string HeaderVersion { get; set; }
[XmlElement(ElementName = "Sender")]
public Sender Sender { get; set; }
}
[XmlRoot(ElementName = "inventoryReportMessage", Namespace = "urn:gs1:ecom:inventory_report:xsd:3")]
public class InventoryReportMessage
{
[XmlElement("StandardBusinessDocumentHeader", Namespace = "http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader")]
public StandartBusinessDocumentHeader Header { get; set; }
}
then serialize those as below:
var report = new InventoryReportMessage
{
Header = new StandartBusinessDocumentHeader {
HeaderVersion = "Standard Business Header version 1.3",
Sender = new Sender
{
Identifier = new Identifier
{
Authority = "GS1",
Value = "0000"
},
ContactInformation = new ContactInformation
{
Contact = "some one",
EmailAddress = "someone#example.com",
TelephoneNumber = "00357",
ContactTypeIdentifier = "IT Support"
}
}
}
};
using (var stream = new MemoryStream())
{
using (var writer = new StreamWriter(stream))
{
var settings = new XmlWriterSettings {
Indent = true
};
using (var xmlWriter = XmlWriter.Create(writer, settings))
{
xmlWriter.WriteStartDocument(false);
var serializer = new XmlSerializer(typeof(InventoryReportMessage));
var namespaces = new XmlSerializerNamespaces();
namespaces.Add("inventory_report", "urn:gs1:ecom:inventory_report:xsd:3");
namespaces.Add("sh", "http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader");
namespaces.Add("ecom_common", "urn:gs1:ecom:ecom_common:xsd:3");
namespaces.Add("shared_common", "urn:gs1:shared:shared_common:xsd:3");
serializer.Serialize(xmlWriter, report, namespaces);
}
stream.Position = 0;
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
Console.ReadLine();
Using xml linq. I like to create a string header and then add dynamic values in code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string header =
"<inventory_report:inventoryReportMessage xmlns:inventory_report=\"urn:gs1:ecom:inventory_report:xsd:3\" xmlns:sh=\"http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader\" xmlns:ecom_common=\"urn:gs1:ecom:ecom_common:xsd:3\" xmlns:shared_common=\"urn:gs1:shared:shared_common:xsd:3\">" +
"<sh:StandardBusinessDocumentHeader>" +
"<sh:HeaderVersion>Standard Business Header version 1.3</sh:HeaderVersion>" +
"<sh:Sender>" +
"</sh:Sender>" +
"</sh:StandardBusinessDocumentHeader>" +
"</inventory_report:inventoryReportMessage>";
XDocument doc = XDocument.Parse(header);
XElement sender = doc.Descendants().Where(x => x.Name.LocalName == "Sender").FirstOrDefault();
XNamespace shNs = sender.GetNamespaceOfPrefix("sh");
sender.Add(new XElement(shNs + "Identifier", new object[] {
new XAttribute("Authority", "GS1"),
"0000"
}));
sender.Add( new XElement(shNs + "ContactInformation", new object[] {
new XElement(shNs + "Contact", "some one"),
new XElement(shNs + "EmailAddress", "someone#example.com"),
new XElement(shNs + "TelephoneNumber", "00357"),
new XElement(shNs + "ContactTypeOdemtofier", "IT Support")
}));
}
}
}
I am creating XML to send data. The data contains multiple datatypes as string, integer and decimal. My XML format and c# code to create it as follows.
<root>
<data>
<struct>
<PartnerCD></PartnerCD>
<UserName> </UserName>
<Password> </Password>
<Action> </Action>
<OfficeCD></OfficeCD>
<ChannelCD></ChannelCD>
<Token></Token>
<Notes> </Notes>
<Products>
<Product>
<ProductID></ProductID>
<SVA></SVA>
<Amount></Amount>
</Product>
</Products>
</struct>
</data>
</root>
And my c# code is
public static string CreateRequestXML(string partnerCd, string userName, string password, string action, string productId, string token, string sva, string amount)
{
XmlDocument doc = new XmlDocument();
XmlElement elemRoot = doc.CreateElement("root");
XmlElement elemData = doc.CreateElement("data");
XmlElement elemStruct = doc.CreateElement("struct");
XmlElement elemProducts = doc.CreateElement("Products");
XmlElement elemProduct = doc.CreateElement("Product");
doc.AppendChild(elemRoot);
elemRoot.AppendChild(elemData);
elemData.AppendChild(elemStruct);
//Insert data here
InsertDataNode(doc, elemStruct, "PartnerCD", partnerCd);
InsertDataNode(doc, elemStruct, "UserName", userName);
InsertDataNode(doc, elemStruct, "Password", password);
InsertDataNode(doc, elemStruct, "Action", action);
InsertDataNode(doc, elemStruct, "Token", token);
elemStruct.AppendChild(elemProducts);
elemProducts.AppendChild(elemProduct);
InsertDataNode(doc, elemProduct, "ProductID", productId);
InsertDataNode(doc, elemProduct, "SVA", sva);
InsertDataNode(doc, elemProduct, "Amount", amount);
return doc.OuterXml;
}
private static void InsertDataNode(XmlDocument doc, XmlElement parentElem, string nodeName, string nodeValue)
{
XmlElement elem = doc.CreateElement(nodeName);
elem.InnerText = nodeValue;
parentElem.AppendChild(elem);
}
and am getting the result as
<root>
<data>
<struct>
<PartnerCD>123</PartnerCD>
<UserName>api</UserName>
<Password>pass</Password>
<Action>token</Action>
<Token>4847898</Token>
<Products>
<Product>
<ProductID>123</ProductID>
<SVA>e8a8227c-bba3-4f32-a2cd-15e8f246344b</SVA>
<Amount>700</Amount>
</Product>
</Products>
</struct>
</data>
</root>
I want the PartnerCD and ProductId elements as integer and Amount element as decimal. I have tried XMLNodeType but no use.
Well the data type is irrelevant in the XML as such, it's all defined in the schema it uses, that's where the declaration of expected data types are stored.
So if you have a XSD that says that /root/data/struct/PartnerCD is of type xs:int then you will get validation errors upon validating the file. The XML itself is just a container of all data, it doesn't include the meta information. You CAN define it manually, but the Point is beyond me in about 99.99% of the cases, and it's more or less a bastard of XML, like MSXML that will understand what you're up to.
Xml has no concept of "data type" natively, the XmlNodeType you refer to is what type of Node it is (such as element, attribute etc), not what type of data is contained within it.
Personally I would create an object and Serialize\Deserialize to\from XML like so.....
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.IO;
namespace _37321906
{
class Program
{
static void Main(string[] args)
{
Root root = new Root();
root.Data.Struct.PartnerCD = 123;
root.Data.Struct.UserName = "api";
root.Data.Struct.Password = "pass";
root.Data.Struct.Action = "token";
root.Data.Struct.Token = 4847898;
root.Data.Struct.Products.Product.Add(new Product { ProductID = 123, SVA = "e8a8227c-bba3-4f32-a2cd-15e8f246344b", Amount = 700.0001 });
// Serialize the root object to XML
Serialize<Root>(root);
// Deserialize from XML
Root DeserializeRoot = Deserialize<Root>();
}
private static void Serialize<T>(T data)
{
// Use a file stream here.
using (TextWriter WriteFileStream = new StreamWriter("test.xml"))
{
// Construct a SoapFormatter and use it
// to serialize the data to the stream.
XmlSerializer SerializerObj = new XmlSerializer(typeof(T));
try
{
// Serialize EmployeeList to the file stream
SerializerObj.Serialize(WriteFileStream, data);
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Failed to serialize. Reason: {0}", ex.Message));
}
}
}
private static T Deserialize<T>() where T : new()
{
//List<Employee> EmployeeList2 = new List<Employee>();
// Create an instance of T
T ReturnListOfT = CreateInstance<T>();
// Create a new file stream for reading the XML file
using (FileStream ReadFileStream = new FileStream("test.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
{
// Construct a XmlSerializer and use it
// to serialize the data from the stream.
XmlSerializer SerializerObj = new XmlSerializer(typeof(T));
try
{
// Deserialize the hashtable from the file
ReturnListOfT = (T)SerializerObj.Deserialize(ReadFileStream);
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Failed to serialize. Reason: {0}", ex.Message));
}
}
// return the Deserialized data.
return ReturnListOfT;
}
// function to create instance of T
public static T CreateInstance<T>() where T : new()
{
return (T)Activator.CreateInstance(typeof(T));
}
}
[XmlRoot(ElementName = "Product")]
public class Product
{
[XmlElement(ElementName = "ProductID")]
public int ProductID { get; set; }
[XmlElement(ElementName = "SVA")]
public string SVA { get; set; }
[XmlElement(ElementName = "Amount")]
public double Amount { get; set; }
}
[XmlRoot(ElementName = "Products")]
public class Products
{
public Products()
{
this.Product = new List<Product>();
}
[XmlElement(ElementName = "Product")]
public List<Product> Product { get; set; }
}
[XmlRoot(ElementName = "struct")]
public class Struct
{
public Struct()
{
this.Products = new Products();
}
[XmlElement(ElementName = "PartnerCD")]
public int PartnerCD { get; set; }
[XmlElement(ElementName = "UserName")]
public string UserName { get; set; }
[XmlElement(ElementName = "Password")]
public string Password { get; set; }
[XmlElement(ElementName = "Action")]
public string Action { get; set; }
[XmlElement(ElementName = "OfficeCD")]
public string OfficeCD { get; set; }
[XmlElement(ElementName = "ChannelCD")]
public string ChannelCD { get; set; }
[XmlElement(ElementName = "Token")]
public int Token { get; set; }
[XmlElement(ElementName = "Notes")]
public string Notes { get; set; }
[XmlElement(ElementName = "Products")]
public Products Products { get; set; }
}
[XmlRoot(ElementName = "data")]
public class Data
{
public Data()
{
this.Struct = new Struct();
}
[XmlElement(ElementName = "struct")]
public Struct Struct { get; set; }
}
[XmlRoot(ElementName = "root")]
public class Root
{
public Root()
{
this.Data = new Data();
}
[XmlElement(ElementName = "data")]
public Data Data { get; set; }
}
}
find your XML in the build folder called test.xml