Create generic classes for nested XML - c#

I might going wrong direction, but I want to create generic classes for following XML structure.
<?xml version="1.0" encoding="UTF-8"?>
<root>
<success>true</success>
<data>
<item>
<Barcode>20450004941980</Barcode>
<ChildDocuments>
<success>true</success>
<data>
<item>
<StateId>10</StateId>
</item>
</data>
<errors />
<warnings />
<info />
</ChildDocuments>
</item>
</data>
<errors />
<warnings />
<info />
</root>
There could be more elements in as well as in ChildDocuments. I've created following structure:
[Serializable()]
[System.Xml.Serialization.XmlRoot("root")]
public class XmlRoot<T>
{
public XmlRoot()
{
DataArray = new List<T>();
}
[XmlElement("data")]
public List<T> DataArray { get; set; }
}
[Serializable()]
public class XmlRootData<T>
{
public XmlRootData()
{
ItemArray = new List<T>();
}
[XmlElement("item")]
public List<T> ItemArray { get; set; }
}
and now I am thinking how to create something generic for ChildDocument. Basically it has the same generic structure as the root document.So far I know that there could be only 1 level for ChildDocument, so I can create 2 more generic classes, something like:
[Serializable()]
public class XmlRootData<T,U>
{
public XmlRootData()
{
ItemArray = new List<T>();
}
[XmlElement("item")]
public List<T> ItemArray { get; set; }
public List<XmlRoot<U>> ChildDataRoot { get; set; }
}
I can create 2 more extra classes for Child inner xml, however I am not 100% sure that there could be max 2 levels...

If generating class thru tools for your xml is an option then you can follow below steps. It will help if you have real xml file with complete data. I have given a shot based on the xml file passed in the question.
Create XSD from XML file
From XSD Create Class for it
And below is the generated Class, now based on this class you can adjust your class or use the below class as is. You can also rename the properties and customize all the names by decorating them with appropriate attributes.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=4.6.81.0.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.81.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class root {
private bool successField;
private rootData dataField;
private object errorsField;
private object warningsField;
private object infoField;
/// <remarks/>
public bool success {
get {
return this.successField;
}
set {
this.successField = value;
}
}
/// <remarks/>
public rootData data {
get {
return this.dataField;
}
set {
this.dataField = value;
}
}
/// <remarks/>
public object errors {
get {
return this.errorsField;
}
set {
this.errorsField = value;
}
}
/// <remarks/>
public object warnings {
get {
return this.warningsField;
}
set {
this.warningsField = value;
}
}
/// <remarks/>
public object info {
get {
return this.infoField;
}
set {
this.infoField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.81.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class rootData {
private rootDataItem itemField;
/// <remarks/>
public rootDataItem item {
get {
return this.itemField;
}
set {
this.itemField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.81.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class rootDataItem {
private ulong barcodeField;
private rootDataItemChildDocuments childDocumentsField;
/// <remarks/>
public ulong Barcode {
get {
return this.barcodeField;
}
set {
this.barcodeField = value;
}
}
/// <remarks/>
public rootDataItemChildDocuments ChildDocuments {
get {
return this.childDocumentsField;
}
set {
this.childDocumentsField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.81.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class rootDataItemChildDocuments {
private bool successField;
private rootDataItemChildDocumentsData dataField;
private object errorsField;
private object warningsField;
private object infoField;
/// <remarks/>
public bool success {
get {
return this.successField;
}
set {
this.successField = value;
}
}
/// <remarks/>
public rootDataItemChildDocumentsData data {
get {
return this.dataField;
}
set {
this.dataField = value;
}
}
/// <remarks/>
public object errors {
get {
return this.errorsField;
}
set {
this.errorsField = value;
}
}
/// <remarks/>
public object warnings {
get {
return this.warningsField;
}
set {
this.warningsField = value;
}
}
/// <remarks/>
public object info {
get {
return this.infoField;
}
set {
this.infoField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.81.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class rootDataItemChildDocumentsData {
private rootDataItemChildDocumentsDataItem itemField;
/// <remarks/>
public rootDataItemChildDocumentsDataItem item {
get {
return this.itemField;
}
set {
this.itemField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.81.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class rootDataItemChildDocumentsDataItem {
private byte stateIdField;
/// <remarks/>
public byte StateId {
get {
return this.stateIdField;
}
set {
this.stateIdField = value;
}
}
}

Related

XML deserialization in C# is returning null array even when XML has data

I'm trying to deserialize an XML
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="urn:Magento" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:catalogProductListResponse>
<storeView SOAP-ENC:arrayType="ns1:catalogProductEntity[609]" xsi:type="ns1:catalogProductEntityArray">
<item xsi:type="ns1:catalogProductEntity">
<product_id xsi:type="xsd:string">36</product_id>
<sku xsi:type="xsd:string">000975</sku>
<name xsi:type="xsd:string">Beauty Dermo HTM - Vacuoterapia</name>
<set xsi:type="xsd:string">4</set>
<type xsi:type="xsd:string">simple</type>
<category_ids SOAP-ENC:arrayType="xsd:string[9]" xsi:type="ns1:ArrayOfString">
<item xsi:type="xsd:string">4</item>
</category_ids>
<website_ids SOAP-ENC:arrayType="xsd:string[1]" xsi:type="ns1:ArrayOfString">
<item xsi:type="xsd:string">1</item>
</website_ids>
</item>
<item xsi:type="ns1:catalogProductEntity">
<product_id xsi:type="xsd:string">37</product_id>
<sku xsi:type="xsd:string">004279</sku>
<name xsi:type="xsd:string">Effect HTM - Radiofrequência</name>
<set xsi:type="xsd:string">4</set>
<type xsi:type="xsd:string">simple</type>
<category_ids SOAP-ENC:arrayType="xsd:string[8]" xsi:type="ns1:ArrayOfString">
<item xsi:type="xsd:string">4</item>
</category_ids>
<website_ids SOAP-ENC:arrayType="xsd:string[1]" xsi:type="ns1:ArrayOfString">
<item xsi:type="xsd:string">1</item>
</website_ids>
</item>
...[OTHER MANY ITENS]
</storeView>
</ns1:catalogProductListResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
In this class
public class ProductListResponse
{
// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.xmlsoap.org/soap/envelope/", IsNullable = false)]
public partial class Envelope
{
private EnvelopeBody bodyField;
private string encodingStyleField;
/// <remarks/>
public EnvelopeBody Body
{
get
{
return this.bodyField;
}
set
{
this.bodyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified)]
public string encodingStyle
{
get
{
return this.encodingStyleField;
}
set
{
this.encodingStyleField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public partial class EnvelopeBody
{
private catalogProductListResponse catalogProductListResponseField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "urn:Magento")]
public catalogProductListResponse catalogProductListResponse
{
get
{
return this.catalogProductListResponseField;
}
set
{
this.catalogProductListResponseField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "urn:Magento")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "urn:Magento", IsNullable = false)]
public partial class catalogProductListResponse
{
private storeView storeViewField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("storeView")]
public storeView storeView
{
get
{
return this.storeViewField;
}
set
{
this.storeViewField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(TypeName = "catalogProductEntityArray")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class storeView
{
private storeViewItem[] itemField;
private string arrayTypeField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("item")]
public storeViewItem[] item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified, Namespace = "http://schemas.xmlsoap.org/soap/encoding/")]
public string arrayType
{
get
{
return this.arrayTypeField;
}
set
{
this.arrayTypeField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(TypeName = "catalogProductEntity")]
public partial class storeViewItem
{
private ushort product_idField;
private string skuField;
private string nameField;
private byte setField;
private string typeField;
private storeViewItemCategory_ids category_idsField;
private storeViewItemWebsite_ids website_idsField;
/// <remarks/>
public ushort product_id
{
get
{
return this.product_idField;
}
set
{
this.product_idField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(IsNullable = true)]
public string sku
{
get
{
return this.skuField;
}
set
{
this.skuField = value;
}
}
/// <remarks/>
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
public byte set
{
get
{
return this.setField;
}
set
{
this.setField = value;
}
}
/// <remarks/>
public string type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
/// <remarks/>
public storeViewItemCategory_ids category_ids
{
get
{
return this.category_idsField;
}
set
{
this.category_idsField = value;
}
}
/// <remarks/>
public storeViewItemWebsite_ids website_ids
{
get
{
return this.website_idsField;
}
set
{
this.website_idsField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class storeViewItemCategory_ids
{
private byte[] itemField;
private string arrayTypeField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("item")]
public byte[] item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified, Namespace = "http://schemas.xmlsoap.org/soap/encoding/")]
public string arrayType
{
get
{
return this.arrayTypeField;
}
set
{
this.arrayTypeField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class storeViewItemWebsite_ids
{
private byte itemField;
private string arrayTypeField;
/// <remarks/>
public byte item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified, Namespace = "http://schemas.xmlsoap.org/soap/encoding/")]
public string arrayType
{
get
{
return this.arrayTypeField;
}
set
{
this.arrayTypeField = value;
}
}
}
}
With the code
var deserializedDocument = SerializacaoHelper.Deserialize<ProductListResponse.Envelope>(xmlDocument);
public static T Deserialize<T>(XmlDocument xmlDoc)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
MemoryStream xmlStream = new MemoryStream();
xmlDoc.Save(xmlStream);
xmlStream.Position = 0;
T obj = (T)serializer.Deserialize(xmlStream);
xmlStream.Flush();
return obj;
}
The class was generated with the Visual Studio automatic generator. To simulate it is due, with the XML in the clipboard, to follow the steps Edit > Paste Special > Paste XML as Classes.
The function that deserializes is being executed, however, the storeView attribute is null, even having child nodes inside it in the XML.
Where is the error? In class? In the deserialization code? I can not understand why the StoreView attribute is null if in XML it has data.

How to Deserialize XML Attributes into objects, then iterate through the objects

I would like to be able to 'do things' to the Vehicles in the XML file. Ideally I want to iterate through all the vehicles and do a calculation on their price, and change whether they are OnSale. These values would then be displayed in the UI. My code deserializes the XML file but I am unable to access any of the attributes for the Vehicle. I do not need to serialize the objects back to XML.
I have tried to Console.WriteLine the Price, however when I run the code it is returned as 0. Should I be creating an Array of ResponseGeographyVendorRegionVehicle? and then somehow adding objects of that type to the array?
This is the XML File:
<?xml version="1.0" encoding="utf-8" ?>
<Response>
<Geography>
<Vendor id="JOHN">
<Region id="1"></Region>
<Region id="2">
<Vehicle Make="HONDA" Fuel="Gas" Price="12000" OnSale="Y" Account="JOHNH" />
<Vehicle Make="ACURA" Fuel="Gas" Price="14100" OnSale="Y" Account="JOHNH" />
<Vehicle Make="TOYOTA" Fuel="Gas" Price="8000" OnSale="N" Account="JOHNH" />
<Vehicle Make="HYUNDAI" Fuel="Gas" Price="13000" OnSale="Y" Account="JOHNH" />
<Vehicle Make="INFINITY" Fuel="Gas" Price="16000" OnSale="N" Account="JOHNH" />
</Region>
<Region id="3"></Region>
<Region id="4"></Region>
</Vendor>
</Geography>
</Response>
This is my Program.cs:
namespace XMLDeserializeExample
{
class Program
{
static void Main(string[] args)
{
string path = #"c:\XMLFile1.xml";
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Response";
XmlSerializer ser = new XmlSerializer(typeof(ResponseGeographyVendorRegionVehicle), xRoot);
ResponseGeographyVendorRegionVehicle i;
using (Stream reader = new FileStream(path,FileMode.Open))
{
i = (ResponseGeographyVendorRegionVehicle)ser.Deserialize(reader);
Console.WriteLine(i.Price);
Console.ReadLine();
}
}
}
}
This is the Paste Special Response.CS file that was created:
namespace XMLDeserializeExample
{
}
// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Response
{
private ResponseGeography geographyField;
/// <remarks/>
public ResponseGeography Geography
{
get
{
return this.geographyField;
}
set
{
this.geographyField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ResponseGeography
{
private ResponseGeographyVendor vendorField;
/// <remarks/>
public ResponseGeographyVendor Vendor
{
get
{
return this.vendorField;
}
set
{
this.vendorField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ResponseGeographyVendor
{
private ResponseGeographyVendorRegion[] regionField;
private string idField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Region")]
public ResponseGeographyVendorRegion[] Region
{
get
{
return this.regionField;
}
set
{
this.regionField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id
{
get
{
return this.idField;
}
set
{
this.idField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ResponseGeographyVendorRegion
{
private ResponseGeographyVendorRegionVehicle[] vehicleField;
private byte idField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Vehicle")]
public ResponseGeographyVendorRegionVehicle[] Vehicle
{
get
{
return this.vehicleField;
}
set
{
this.vehicleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public byte id
{
get
{
return this.idField;
}
set
{
this.idField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ResponseGeographyVendorRegionVehicle
{
private string makeField;
private string fuelField;
private ushort priceField;
private string onSaleField;
private string accountField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Make
{
get
{
return this.makeField;
}
set
{
this.makeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Fuel
{
get
{
return this.fuelField;
}
set
{
this.fuelField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public ushort Price
{
get
{
return this.priceField;
}
set
{
this.priceField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string OnSale
{
get
{
return this.onSaleField;
}
set
{
this.onSaleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Account
{
get
{
return this.accountField;
}
set
{
this.accountField = value;
}
}
}
Please let me know how I can better explain myself. Apologies if none of this makes sense- welcome to my weekend lol.
Thank you.
As your xml-root is obviously a Response instead of a ResponseGeographyVendor you have to de-serialize to that type:
string path = #"c:\XMLFile1.xml";
XmlSerializer ser = new XmlSerializer(typeof(response);
ResponseGeographyVendor i;
using (Stream reader = new FileStream(path,FileMode.Open))
{
i = ((Response)ser.Deserialize(reader)).Geography.Vendor;
Console.WriteLine(i.Price);
Console.ReadLine();
}
A serializer will only work on the entire xml-document. You can´t just write or read parts of it. So just use the xml, serialize it to an instance of Response and get its Geography-member.
Now you can easily get the 3rd Vehicle within the second Region:
var vehicle = i.Region[1].Vehicle[2];
Notice that you don´t need to provide the xml-root yourself.
You'll want to use the XML Serializer that's built into .Net.
First create a class to represent the XML document data:
public class Response
{
public Geography Geography {get; set;}
}
public class Geography
{
public Vendor Vendor{get;set;}
}
public class Vendor
{
public List<Region> Regions {get;set;}
}
public class Region
{
}
and so on.
Then read the xml as a string and deserialize it:
string myXml = File.ReadAsStringAsync(filepath).Result;
XmlSerializer ser = new XmlSerializer(typeof(Response));
using (TextReader reader = new StringReader(myXml)
{
Response myResponse = ser.Deserialize(reader);
}
Then you can iterate through all the properties and stuff on the Geography object.

XML deserialization stuck

I've generated a xsd file from xml and then priceResponse.cs from xsd file using xsd.exe.
Here is priceResponse.cs code:
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=4.6.1055.0.
//
/// <uwagi/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class document {
private object[] itemsField;
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute("DATASETS", typeof(documentDATASETS), Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlElementAttribute("ERROR", typeof(documentERROR), Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlElementAttribute("PRICE", typeof(documentPRICE), Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public object[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
/// <uwagi/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class documentDATASETS {
private string cOUNTRYField;
private string cURRENCYField;
private string pOSTCODEMASKField;
private string tOWNGROUPField;
private string sERVICEField;
private string oPTIONField;
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string COUNTRY {
get {
return this.cOUNTRYField;
}
set {
this.cOUNTRYField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string CURRENCY {
get {
return this.cURRENCYField;
}
set {
this.cURRENCYField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string POSTCODEMASK {
get {
return this.pOSTCODEMASKField;
}
set {
this.pOSTCODEMASKField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string TOWNGROUP {
get {
return this.tOWNGROUPField;
}
set {
this.tOWNGROUPField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string SERVICE {
get {
return this.sERVICEField;
}
set {
this.sERVICEField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string OPTION {
get {
return this.oPTIONField;
}
set {
this.oPTIONField = value;
}
}
}
/// <uwagi/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class documentERROR {
private string cODEField;
private string dESCRIPTIONField;
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string CODE {
get {
return this.cODEField;
}
set {
this.cODEField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string DESCRIPTION {
get {
return this.dESCRIPTIONField;
}
set {
this.dESCRIPTIONField = value;
}
}
}
/// <uwagi/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class documentPRICE {
private string rATEIDField;
private string sERVICEField;
private string sERVICEDESCField;
private string oPTIONField;
private string oPTIONDESCField;
private string cURRENCYField;
private string rATEField;
private string rESULTField;
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string RATEID {
get {
return this.rATEIDField;
}
set {
this.rATEIDField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string SERVICE {
get {
return this.sERVICEField;
}
set {
this.sERVICEField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string SERVICEDESC {
get {
return this.sERVICEDESCField;
}
set {
this.sERVICEDESCField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string OPTION {
get {
return this.oPTIONField;
}
set {
this.oPTIONField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string OPTIONDESC {
get {
return this.oPTIONDESCField;
}
set {
this.oPTIONDESCField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string CURRENCY {
get {
return this.cURRENCYField;
}
set {
this.cURRENCYField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string RATE {
get {
return this.rATEField;
}
set {
this.rATEField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string RESULT {
get {
return this.rESULTField;
}
set {
this.rESULTField = value;
}
}
}
I'm trying to deserialize priceResponse.xml but It seems like it is stuck. I think there is problem with namespaces and I'm doing deserialization wrong.
Here is xml code:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<document>
<DATASETS>
<COUNTRY>UTD</COUNTRY>
<CURRENCY>UTD</CURRENCY>
<POSTCODEMASK>UTD</POSTCODEMASK>
<TOWNGROUP>UTD</TOWNGROUP>
<SERVICE>UTD</SERVICE>
<OPTION>UTD</OPTION>
</DATASETS>
<ERROR>
<CODE>P13</CODE>
<DESCRIPTION>RATEID: 1 - Standard Rates</DESCRIPTION>
</ERROR>
<PRICE>
<RATEID>1</RATEID>
<SERVICE>09N</SERVICE>
<SERVICEDESC>9:00 Express</SERVICEDESC>
<OPTION>NONE</OPTION>
<OPTIONDESC>NONE</OPTIONDESC>
<CURRENCY>PLN</CURRENCY>
<RATE>712.93</RATE>
<RESULT>Y</RESULT>
</PRICE>
<PRICE>
<RATEID>1</RATEID>
<SERVICE>10N</SERVICE>
<SERVICEDESC>10:00 Express</SERVICEDESC>
<OPTION>NONE</OPTION>
<OPTIONDESC>NONE</OPTIONDESC>
<CURRENCY>PLN</CURRENCY>
<RATE>706.14</RATE>
<RESULT>Y</RESULT>
</PRICE>
<PRICE>
<RATEID>1</RATEID>
<SERVICE>12N</SERVICE>
<SERVICEDESC>12:00 Express</SERVICEDESC>
<OPTION>NONE</OPTION>
<OPTIONDESC>NONE</OPTIONDESC>
<CURRENCY>PLN</CURRENCY>
<RATE>689.84</RATE>
<RESULT>Y</RESULT>
</PRICE>
<PRICE>
<RATEID>1</RATEID>
<SERVICE>15N</SERVICE>
<SERVICEDESC>Express</SERVICEDESC>
<OPTION>NONE</OPTION>
<OPTIONDESC>NONE</OPTIONDESC>
<CURRENCY>PLN</CURRENCY>
<RATE>670.03</RATE>
<RESULT>Y</RESULT>
</PRICE>
</document>
And finally deserialization code:
File.WriteAllText("priceResponse.xml", x);
//Console.WriteLine(x);
var ser = new XmlSerializer(typeof(document),new XmlRootAttribute("documentPRICE"));
using (var reader = XmlReader.Create("priceResponse.xml"))
{
var wrapper = (document)ser.Deserialize(reader);
foreach (documentPRICE item in wrapper.Items)
{
Console.WriteLine(item.OPTIONDESC);
}
}
I would like to get each items in PRICE element, but I can't deserialize xml. What am I doing wrong ?
In this line of code,
var ser = new XmlSerializer(typeof(document),new XmlRootAttribute("documentPRICE"));
you have serialized the document object but are keeping the root of the xml as documentPRICE. And here,
var wrapper = (document)ser.Deserialize(reader);
you are trying to deserialize it to document object which does not make sense.
The xml created after serializing in your case has documentPRICE as the root object but you are trying to deserialize the same to document object, which is wrong. What you need to do is to keep document as the root while serializing ,as below.
var ser = new XmlSerializer(typeof(document), new XmlRootAttribute("document"));
And it should work.

Complex XML deserialization

I'm trying to deserialize a complex XML file. i have my main class structured so it gets all of the info in the first child nodes, I even have it so that i can obtain the ClientName which is two layers deep. However, anything beyond that does not seem to work. I get a List item with a count of 1 but no information is inside the list.
My OrderTaxes and OrderTransactions lists come back with a Count = 1 but all of the fields are null.
I'm positive it is a problem with my class structure and any help towards correcting this would be very appreciated.
Here is the XML:
<OrderDetail>
<MessageTypeCode>82540</MessageTypeCode>
<OrderDetailId>59339463</OrderDetailId>
<ClientInfo>
<ClientName>LenderName will appear here</ClientName>
</ClientInfo>
<OrderTaxes>
<OrderTax>
<TaxId>9202225</TaxId>
</OrderTax>
</OrderTaxes>
<OrderTransactions>
<OrderTransaction>
<LoanAmount/>
<Title>
<TitleVendors>
<TitleVendor>
<VendorInstructions>blah blah blah blah .</VendorInstructions>
<VendorServices>
<TitleVendorService>
<TitleVendorServiceId>6615159</TitleVendorServiceId>
<ServiceCode>1OWNER</ServiceCode>
<CustomVendorInstructions>blah blah blah blah blah </CustomVendorInstructions>
</TitleVendorService>
</VendorServices>
</TitleVendor>
</TitleVendors>
</Title>
</OrderTransaction>
</OrderTransactions>
</OrderDetail>
And here is the class:
namespace TSIxmlParser
{
[XmlRoot("OrderDetail")]
public class OrderData
{
[XmlElement("MessageTypeCode")]
public string MessageTypeCode { get; set; }
[XmlElement("OrderDetailId")]
public string OrderNumber { get; set; }
[XmlElement("ClientInfo")]
public List<ClientInfo> ClientInfos = new List<ClientInfo>();
[XmlArray("OrderTaxes")]
[XmlArrayItem("OrderTax")]
public List<OrderTax> OrderTaxes = new List<OrderTax>();
[XmlArray("OrderTransactions")]
[XmlArrayItem("OrderTransaction")]
public List<OrderTransaction> OrderTransactions = new List<OrderTransaction>();
}
public class ClientInfo
{
[XmlElement("ClientName")]
public string ClientName { get; set; }
}
public class OrderTax
{
[XmlElement("TaxId")]
public string TaxId { get; set; }
}
public class OrderTransaction
{
[XmlElement("LoanAmount")]
public string LoanAmount { get; set; }
[XmlArray("Title")]
[XmlArrayItem("TitleVendors")]
public List<Title> Titles { get; set; }
}
public class Title
{
[XmlArrayItem("TitleVendors")]
public List<TitleVendors> TitleVendors { get; set; }
}
public class TitleVendors
{
[XmlArray("TitleVendor")]
public List<TitleVendor> TitleVendor { get; set; }
}
public class TitleVendor
{
[XmlElement("VendorInstructions")]
public string VendorInstructions { get; set; }
[XmlArray("VendorServices")]
[XmlArrayItem("TitleVendorService")]
public List<TitleVendorService> VendorServices { get; set; }
}
public class TitleVendorService
{
[XmlElement("TitleVendorServiceId")]
public string TitleVendorServiceId { get; set; }
[XmlElement("ServiceCode")]
public string ServiceCode { get; set; }
[XmlElement("CustomVendorInstructions")]
public string CustomVendorInstructions { get; set; }
}
}
The .NET SDK provides a great tool for this. The XML Schedma Definition Tool (csd.exe).
More Info: http://msdn.microsoft.com/en-us/library/x6c1kb0s(v=vs.110).aspx
I ran through an example using your XML to show you have it works.
First I saved your XML to my desktop to a file named 'sample.xml'
I opened up the VS 2012 Command Prompt as Administrator.
In the Command Prompt, I navigated to the directory where the SDK is installed. For me its installed here (might be different with various OS or VS versions):
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools
I ran the following command to create an XSD for your XML. (Expect sample.xsd to appear on the desktop)
xsd "c:\users\glenn\desktop\sample.xml" /outputdir:"c:\users\glenn\desktop"
I ran the following command to create a CSharp file from the resultant XSD file.
xsd "c:\users\glenn\desktop\sample.xsd" /classes /outputdir:"c:\users\glenn\desktop"
Excluding the comments, this is the CSharp file that is custom generated for your XML schema. There are additional options to set the namespace and typename. Please review the article above for that detail.
using System.Xml.Serialization;
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class OrderDetail {
private string messageTypeCodeField;
private string orderDetailIdField;
private OrderDetailClientInfo[] clientInfoField;
private OrderDetailOrderTaxesOrderTax[][] orderTaxesField;
private OrderDetailOrderTransactionsOrderTransaction[][] orderTransactionsField;
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string MessageTypeCode {
get {
return this.messageTypeCodeField;
}
set {
this.messageTypeCodeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string OrderDetailId {
get {
return this.orderDetailIdField;
}
set {
this.orderDetailIdField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ClientInfo", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public OrderDetailClientInfo[] ClientInfo {
get {
return this.clientInfoField;
}
set {
this.clientInfoField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlArrayItemAttribute("OrderTax", typeof(OrderDetailOrderTaxesOrderTax), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]
public OrderDetailOrderTaxesOrderTax[][] OrderTaxes {
get {
return this.orderTaxesField;
}
set {
this.orderTaxesField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlArrayItemAttribute("OrderTransaction", typeof(OrderDetailOrderTransactionsOrderTransaction), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]
public OrderDetailOrderTransactionsOrderTransaction[][] OrderTransactions {
get {
return this.orderTransactionsField;
}
set {
this.orderTransactionsField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class OrderDetailClientInfo {
private string clientNameField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string ClientName {
get {
return this.clientNameField;
}
set {
this.clientNameField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class OrderDetailOrderTaxesOrderTax {
private string taxIdField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string TaxId {
get {
return this.taxIdField;
}
set {
this.taxIdField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class OrderDetailOrderTransactionsOrderTransaction {
private string loanAmountField;
private OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendor[][][] titleField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string LoanAmount {
get {
return this.loanAmountField;
}
set {
this.loanAmountField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlArrayItemAttribute("TitleVendors", typeof(OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendor[]), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]
[System.Xml.Serialization.XmlArrayItemAttribute("TitleVendor", typeof(OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendor), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false, NestingLevel=1)]
public OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendor[][][] Title {
get {
return this.titleField;
}
set {
this.titleField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendor {
private string vendorInstructionsField;
private OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServicesTitleVendorService[][] vendorServicesField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string VendorInstructions {
get {
return this.vendorInstructionsField;
}
set {
this.vendorInstructionsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlArrayItemAttribute("TitleVendorService", typeof(OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServicesTitleVendorService), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]
public OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServicesTitleVendorService[][] VendorServices {
get {
return this.vendorServicesField;
}
set {
this.vendorServicesField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServicesTitleVendorService {
private string titleVendorServiceIdField;
private string serviceCodeField;
private string customVendorInstructionsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string TitleVendorServiceId {
get {
return this.titleVendorServiceIdField;
}
set {
this.titleVendorServiceIdField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string ServiceCode {
get {
return this.serviceCodeField;
}
set {
this.serviceCodeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string CustomVendorInstructions {
get {
return this.customVendorInstructionsField;
}
set {
this.customVendorInstructionsField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class NewDataSet {
private OrderDetail[] itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("OrderDetail")]
public OrderDetail[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
Hope this helps!
Try using XmlArray and XmlArrayItem on the corresponding properties.
[XmlArray("OrderTaxes")]
[XmlArrayItem("OrderTax")]
public List<OrderTax> OrderTaxes = new List<OrderTax>();
and
[XmlArray("OrderTransactions")]
[XmlArrayItem("OrderTransaction")]
public List<OrderTransaction> OrderTransactions = new List<OrderTransaction>();
This way the serializer will know that these are to be treated as collections and will know how to look for a specific item.
Besides these two I would say that wherever you are defining a list of elements you should use this approach. TitleVendors most likely will need something similar.
Well, I am not sure if you wanted this (raw dump of deserialized XML):
{
MessageTypeCode: 82540,
OrderDetailId: 59339463,
ClientInfo:
{
ClientName: LenderName will appear here
},
OrderTaxes:
{
OrderTax:
{
TaxId: 9202225
}
},
OrderTransactions:
{
OrderTransaction:
{
LoanAmount: {},
Title:
{
TitleVendors:
{
TitleVendor:
{
VendorInstructions: blah blah blah blah .,
VendorServices:
{
TitleVendorService:
{
TitleVendorServiceId: 6615159,
ServiceCode: 1OWNER,
CustomVendorInstructions: blah blah blah blah blah
}
}
}
}
}
}
}
}
So basically I just used Edit -> Paste special -> Paste XML as Classes:
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class OrderDetail
{
private uint messageTypeCodeField;
private uint orderDetailIdField;
private OrderDetailClientInfo clientInfoField;
private OrderDetailOrderTaxes orderTaxesField;
private OrderDetailOrderTransactions orderTransactionsField;
/// <remarks/>
public uint MessageTypeCode
{
get
{
return this.messageTypeCodeField;
}
set
{
this.messageTypeCodeField = value;
}
}
/// <remarks/>
public uint OrderDetailId
{
get
{
return this.orderDetailIdField;
}
set
{
this.orderDetailIdField = value;
}
}
/// <remarks/>
public OrderDetailClientInfo ClientInfo
{
get
{
return this.clientInfoField;
}
set
{
this.clientInfoField = value;
}
}
/// <remarks/>
public OrderDetailOrderTaxes OrderTaxes
{
get
{
return this.orderTaxesField;
}
set
{
this.orderTaxesField = value;
}
}
/// <remarks/>
public OrderDetailOrderTransactions OrderTransactions
{
get
{
return this.orderTransactionsField;
}
set
{
this.orderTransactionsField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailClientInfo
{
private string clientNameField;
/// <remarks/>
public string ClientName
{
get
{
return this.clientNameField;
}
set
{
this.clientNameField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTaxes
{
private OrderDetailOrderTaxesOrderTax orderTaxField;
/// <remarks/>
public OrderDetailOrderTaxesOrderTax OrderTax
{
get
{
return this.orderTaxField;
}
set
{
this.orderTaxField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTaxesOrderTax
{
private uint taxIdField;
/// <remarks/>
public uint TaxId
{
get
{
return this.taxIdField;
}
set
{
this.taxIdField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTransactions
{
private OrderDetailOrderTransactionsOrderTransaction orderTransactionField;
/// <remarks/>
public OrderDetailOrderTransactionsOrderTransaction OrderTransaction
{
get
{
return this.orderTransactionField;
}
set
{
this.orderTransactionField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTransactionsOrderTransaction
{
private object loanAmountField;
private OrderDetailOrderTransactionsOrderTransactionTitle titleField;
/// <remarks/>
public object LoanAmount
{
get
{
return this.loanAmountField;
}
set
{
this.loanAmountField = value;
}
}
/// <remarks/>
public OrderDetailOrderTransactionsOrderTransactionTitle Title
{
get
{
return this.titleField;
}
set
{
this.titleField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTransactionsOrderTransactionTitle
{
private OrderDetailOrderTransactionsOrderTransactionTitleTitleVendors titleVendorsField;
/// <remarks/>
public OrderDetailOrderTransactionsOrderTransactionTitleTitleVendors TitleVendors
{
get
{
return this.titleVendorsField;
}
set
{
this.titleVendorsField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTransactionsOrderTransactionTitleTitleVendors
{
private OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendor titleVendorField;
/// <remarks/>
public OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendor TitleVendor
{
get
{
return this.titleVendorField;
}
set
{
this.titleVendorField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendor
{
private string vendorInstructionsField;
private OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServices vendorServicesField;
/// <remarks/>
public string VendorInstructions
{
get
{
return this.vendorInstructionsField;
}
set
{
this.vendorInstructionsField = value;
}
}
/// <remarks/>
public OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServices VendorServices
{
get
{
return this.vendorServicesField;
}
set
{
this.vendorServicesField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServices
{
private OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServicesTitleVendorService titleVendorServiceField;
/// <remarks/>
public OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServicesTitleVendorService TitleVendorService
{
get
{
return this.titleVendorServiceField;
}
set
{
this.titleVendorServiceField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServicesTitleVendorService
{
private uint titleVendorServiceIdField;
private string serviceCodeField;
private string customVendorInstructionsField;
/// <remarks/>
public uint TitleVendorServiceId
{
get
{
return this.titleVendorServiceIdField;
}
set
{
this.titleVendorServiceIdField = value;
}
}
/// <remarks/>
public string ServiceCode
{
get
{
return this.serviceCodeField;
}
set
{
this.serviceCodeField = value;
}
}
/// <remarks/>
public string CustomVendorInstructions
{
get
{
return this.customVendorInstructionsField;
}
set
{
this.customVendorInstructionsField = value;
}
}
}
All code used:
var xmlString = #
"<OrderDetail>
<MessageTypeCode>82540</MessageTypeCode>
<OrderDetailId>59339463</OrderDetailId>
<ClientInfo>
<ClientName>LenderName will appear here</ClientName>
</ClientInfo>
<OrderTaxes>
<OrderTax>
<TaxId>9202225</TaxId>
</OrderTax>
</OrderTaxes>
<OrderTransactions>
<OrderTransaction>
<LoanAmount/>
<Title>
<TitleVendors>
<TitleVendor>
<VendorInstructions>blah blah blah blah .</VendorInstructions>
<VendorServices>
<TitleVendorService>
<TitleVendorServiceId>6615159</TitleVendorServiceId>
<ServiceCode>1OWNER</ServiceCode>
<CustomVendorInstructions>blah blah blah blah blah </CustomVendorInstructions>
</TitleVendorService>
</VendorServices>
</TitleVendor>
</TitleVendors>
</Title>
</OrderTransaction>
</OrderTransactions>
</OrderDetail>";
var xml = new OrderDetail();
System.Xml.Serialization.XmlSerializer serializer = new
System.Xml.Serialization.XmlSerializer(typeof(OrderDetail));
using(XmlReader reader = XmlReader.Create(new StringReader(xmlString))) {
xml = (OrderDetail) serializer.Deserialize(reader);
}
var xmlDump = xml.Dump();
Since this is still open I thought I'd throw in a quick answer, suitable for XmlSerializer. In making the classes, I assumed a pattern resembling this:
<Foo>
<Bars>
<Bar>
Means that class "Foo" contains a list of instances of class "Bar". A pattern like this:
<Foo>
<Bar>
Means that class "Foo" contains a single reference to an instance of class "Bar". Thus you should only have a single "Title" inside your "OrderTransaction", not a list of them:
public class OrderDetail
{
public string MessageTypeCode { get; set; }
public string OrderDetailId { get; set; }
public ClientInfo ClientInfo { get; set; }
public List<OrderTax> OrderTaxes { get; set; }
public List<OrderTransaction> OrderTransactions { get; set; }
}
public class OrderTransaction
{
public string LoanAmount { get; set; }
public Title Title { get; set; }
}
public class Title
{
public List<TitleVendor> TitleVendors { get; set; }
}
public class TitleVendor
{
public string VendorInstructions { get; set; }
public List<TitleVendorService> VendorServices { get; set; }
}
public class TitleVendorService
{
public string TitleVendorServiceId { get; set; }
public string ServiceCode { get; set; }
public string CustomVendorInstructions { get; set; }
}
public class ClientInfo
{
public string ClientName { get; set; }
}
public class OrderTax
{
public string TaxId { get; set; }
}
None of the XML-related decorations are actually required. XmlElement and XmlArray are only needed if you want to override XmlSerializer's default choices, for instance to rename the element or to handle arrays with polymorphic elements. You can put them if you want to for clarity, or to protect against renaming the property down the road, but I didn't for simplicity.
Here's the test setup. I create an instance of "OrderDetail" from your string, then re-serialize it to XML, then save the original and rewritten XML as files and diff them in a command prompt window:
public static class TestOrderDetail
{
public static string TestString =
#"<OrderDetail>
<MessageTypeCode>82540</MessageTypeCode>
<OrderDetailId>59339463</OrderDetailId>
<ClientInfo>
<ClientName>LenderName will appear here</ClientName>
</ClientInfo>
<OrderTaxes>
<OrderTax>
<TaxId>9202225</TaxId>
</OrderTax>
</OrderTaxes>
<OrderTransactions>
<OrderTransaction>
<LoanAmount/>
<Title>
<TitleVendors>
<TitleVendor>
<VendorInstructions>blah blah blah blah .</VendorInstructions>
<VendorServices>
<TitleVendorService>
<TitleVendorServiceId>6615159</TitleVendorServiceId>
<ServiceCode>1OWNER</ServiceCode>
<CustomVendorInstructions>blah blah blah blah blah </CustomVendorInstructions>
</TitleVendorService>
</VendorServices>
</TitleVendor>
</TitleVendors>
</Title>
</OrderTransaction>
</OrderTransactions>
</OrderDetail>";
public static void Test()
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(OrderDetail));
OrderDetail orderDetail = (OrderDetail)serializer.Deserialize(new StringReader(TestString));
string newTestString = TestWrite(serializer, orderDetail);
var guid = DateTime.Now.Ticks;
var path = Path.GetTempPath();
var file1 = path + Path.DirectorySeparatorChar + "OldOrderDetail_" + guid.ToString() + ".xml";
var file2 = path + Path.DirectorySeparatorChar + "NewOrderDetail_" + guid.ToString() + ".xml";
File.WriteAllText(file1, TestString);
File.WriteAllText(file2, newTestString);
}
catch (Exception e)
{
Debug.Assert(false, e.ToString());
}
}
private static string TestWrite(XmlSerializer serializer, OrderDetail orderDetail)
{
using (var textWriter = new StringWriter())
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true; // For testing purposes, disable the xml version and encoding declarations.
settings.Indent = true;
settings.IndentChars = " "; // The indentation used in the test string.
using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", ""); // For testing purposes, disable the xmlns:xsi and xmlns:xsd lines, which were not in the test string.
serializer.Serialize(xmlWriter, orderDetail, ns);
}
return textWriter.ToString();
}
}
}
Here's the result of diffing the old and new XML files:
diff OldOrderDetail_635420738451748332.xml NewOrderDetail_635420738451748332.xml
14c14
< <LoanAmount/>
---
> <LoanAmount />
Other than inserting an extra space for formatting in the empty "LoanAmount" element, there's no difference.
Btw XmlSerializer and DataContractSerializer are complete different. According your sample you need to use XmlSeralizer (not DataContractSerializer).
This is what I have so far. This code produces the following structure:
-OrderTransactions (Count = 1)
- Loan Amount = ""
- Titles (Count = 1)
-TitleVendors (Count = 1)
- VendorInstructions = null
- VendorServices (Count = 0)
It seems to be seeing the nodes inside TitleVendors, but it doesn't grab the information.
<OrderTransactions>
<OrderTransaction>
<LoanAmount /> --this may be NULL - this should not cause the message to fail.
<Title>
<TitleVendors>
<TitleVendor>
<VendorInstructions>Endorsements required: EPA, COMP, PUD. **Attention Abstractor: THIS IS A VA LOAN** **Attention Abstractor: If a PRIVATE ROAD EASEMENT exists, please provide any information and copies along with the abstract.</VendorInstructions>
<VendorServices>
<TitleVendorService>
<TitleVendorServiceId>6615159</TitleVendorServiceId>
<ServiceCode>1OWNER</ServiceCode>
<CustomVendorInstructions><p><b>Copies of recital page, legal description and signature pages of all open mortgages must be provided including copies of the legal description and any riders.<br /> <br /> Copies of assignments must be provided for open liens.<br /> <br /> If the property is registered land a copy of the certificate of title must accompany the search</CustomVendorInstructions>
</TitleVendorService>
</VendorServices>
</TitleVendor>
</TitleVendors>
</Title>
</OrderTransaction>
</OrderTransactions>
[XmlArray("OrderTransactions")]
[XmlArrayItem("OrderTransaction")]
public List<OrderTransaction> OrderTransactions = new List<OrderTransaction>();
public class OrderTransaction
{
[XmlElement("LoanAmount")]
[DataMember]
public string LoanAmount { get; set; }
[XmlArray("Title")]
[XmlArrayItem("TitleVendors")]
public List<Title> Titles = new List<Title>();
public class Title
{
[XmlArray("TitleVendor")]
[XmlArrayItem("VendorInstructions")]
//[XmlArrayItem("VendorServices")]
public List<TitleVendor> TitleVendors = new List<TitleVendor>();
public class TitleVendor
{
[XmlElement("VendorInstructions")]
[DataMember]
public string VendorInstructions { get; set; }
[XmlArray("VendorServices")]
[XmlArrayItem("TitleVendorService")]
public List<VendorService> VendorServices = new List<VendorService>();
public class VendorService
{
public List<TitleVendorService> TitleVendorServices = new List<TitleVendorService>();
public class TitleVendorService
{
[XmlElement("TitleVendorServiceId")]
[DataMember]
public string TitleVendorServiceId { get; set; }
[XmlElement("ServiceCode")]
[DataMember]
public string ServiceCode { get; set; }
[XmlElement("CustomVendorInstructions")]
[DataMember]
public string CustomVendorInstructions { get; set; }
}
}
}
}
}

XmlSerialize - Desrialize external XML

I have many files, with the format of:
<?xml version="1.0" encoding="utf-8"?>
<Words>
<word>
<Eng>chain</Eng>
<EngEnd>chained</EngEnd>
<PartOfSpeechEng>verb</PartOfSpeechEng>
<Heb>לקשור עם שרשרת</Heb>
<EngInHeb>צֵ'ין</EngInHeb>
<PartOfSpeechHeb>פועל</PartOfSpeechHeb>
<DicNumber>27</DicNumber>
<Arb>سلسلة</Arb>
<EngInArb>
</EngInArb>
</word>
<word>
<Eng>growl</Eng>
<EngEnd>growls</EngEnd>
<PartOfSpeechEng>verb</PartOfSpeechEng>
<Heb>לנהום</Heb>
<EngInHeb>גְרַאוּל</EngInHeb>
<PartOfSpeechHeb>פועל</PartOfSpeechHeb>
<DicNumber>3</DicNumber>
<Arb>دمدمة/تذمـُّر</Arb>
<EngInArb>
</EngInArb>
</word>
</Words>
I failed to deserialize it into array, can someone help me deserialize it
Thanks
Generated using xsd.exe using schema created by this online tool.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=4.0.30319.1.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class Words {
private WordsWord[] wordField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("word")]
public WordsWord[] word {
get {
return this.wordField;
}
set {
this.wordField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class WordsWord {
private string engField;
private string engEndField;
private string partOfSpeechEngField;
private string hebField;
private string engInHebField;
private string partOfSpeechHebField;
private int dicNumberField;
private string arbField;
private string engInArbField;
/// <remarks/>
public string Eng {
get {
return this.engField;
}
set {
this.engField = value;
}
}
/// <remarks/>
public string EngEnd {
get {
return this.engEndField;
}
set {
this.engEndField = value;
}
}
/// <remarks/>
public string PartOfSpeechEng {
get {
return this.partOfSpeechEngField;
}
set {
this.partOfSpeechEngField = value;
}
}
/// <remarks/>
public string Heb {
get {
return this.hebField;
}
set {
this.hebField = value;
}
}
/// <remarks/>
public string EngInHeb {
get {
return this.engInHebField;
}
set {
this.engInHebField = value;
}
}
/// <remarks/>
public string PartOfSpeechHeb {
get {
return this.partOfSpeechHebField;
}
set {
this.partOfSpeechHebField = value;
}
}
/// <remarks/>
public int DicNumber {
get {
return this.dicNumberField;
}
set {
this.dicNumberField = value;
}
}
/// <remarks/>
public string Arb {
get {
return this.arbField;
}
set {
this.arbField = value;
}
}
/// <remarks/>
public string EngInArb {
get {
return this.engInArbField;
}
set {
this.engInArbField = value;
}
}
}
and you can use it like this
XmlSerializer mySerializer = new XmlSerializer(typeof(Words));
FileStream myFileStream = new FileStream("path_to_xml",FileMode.Open);
Words words = (Words)mySerializer.Deserialize(myFileStream);

Categories

Resources