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.
Related
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.
I am trying to deserialize the following XML
<?xml version="1.0" encoding="UTF-8"?>
<GovTalkMessage xmlns="http://www.govtalk.gov.uk/CM/envelope">
<EnvelopeVersion>2.0</EnvelopeVersion>
<Header>
<MessageDetails>
<Class>DRUG_DATA</Class>
<Qualifier>response</Qualifier>
<Function>submit</Function>
<CorrelationID>BD694DAAA26AA6068EAAAE5C7746CE54</CorrelationID>
<Transformation>XML</Transformation>
</MessageDetails>
<SenderDetails>
<IDAuthentication>
<SenderID />
<Authentication>
<Method />
<Role />
<Value />
</Authentication>
</IDAuthentication>
</SenderDetails>
</Header>
<GovTalkDetails>
<Keys>
<Key Type="SpokeName" />
</Keys>
</GovTalkDetails>
<Body>
<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope">
<S:Body>
<ns2:getGenericDrugsResponse xmlns:ns2="http://webservice.sirkb/">
<return>
<DRUG xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns2:genericDrug">
<GENERIC_DRUG_ID>147</GENERIC_DRUG_ID>
<GENERIC_DRUG_NAME>Amoxicilline 125mg/5ml - 60ml</GENERIC_DRUG_NAME>
</DRUG>
<DRUG xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns2:genericDrug">
<GENERIC_DRUG_ID>149</GENERIC_DRUG_ID>
<GENERIC_DRUG_NAME>Amoxicilline 250mg/5ml - 60ml</GENERIC_DRUG_NAME>
</DRUG>
<DRUG xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns2:genericDrug">
<DOSAGE>10mg/5ml</DOSAGE>
<GENERIC_DRUG_ID>2312</GENERIC_DRUG_ID>
<GENERIC_DRUG_NAME>Vinorelbine (as vinorelbine tartrate)</GENERIC_DRUG_NAME>
<PHARMACEUTICAL_FORM>concentrate for solution for infusion</PHARMACEUTICAL_FORM>
</DRUG>
<DRUG xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns2:genericDrug">
<DOSAGE>100 u/ml (approximately 0.58mg)</DOSAGE>
<GENERIC_DRUG_ID>2313</GENERIC_DRUG_ID>
<GENERIC_DRUG_NAME>Laronidase</GENERIC_DRUG_NAME>
<PHARMACEUTICAL_FORM>concentrate for solution for infusion</PHARMACEUTICAL_FORM>
</DRUG>
<RETURN_STATUS>SUCCESS</RETURN_STATUS>
</return>
</ns2:getGenericDrugsResponse>
</S:Body>
</S:Envelope>
</Body>
</GovTalkMessage>
I have generated the classes through Paste XML as Classes feature of Visual Studio 2017. (Using the xsd.exe is the same) I have not changed the generated classes.
They have the following form:
// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.govtalk.gov.uk/CM/envelope", IsNullable = false)]
public partial class GovTalkMessage
{
private decimal envelopeVersionField;
private GovTalkMessageHeader headerField;
private GovTalkMessageGovTalkDetails govTalkDetailsField;
private GovTalkMessageBody bodyField;
/// <remarks/>
public decimal EnvelopeVersion
{
get
{
return this.envelopeVersionField;
}
set
{
this.envelopeVersionField = value;
}
}
/// <remarks/>
public GovTalkMessageHeader Header
{
get
{
return this.headerField;
}
set
{
this.headerField = value;
}
}
/// <remarks/>
public GovTalkMessageGovTalkDetails GovTalkDetails
{
get
{
return this.govTalkDetailsField;
}
set
{
this.govTalkDetailsField = value;
}
}
/// <remarks/>
public GovTalkMessageBody Body
{
get
{
return this.bodyField;
}
set
{
this.bodyField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageHeader
{
private GovTalkMessageHeaderMessageDetails messageDetailsField;
private GovTalkMessageHeaderSenderDetails senderDetailsField;
/// <remarks/>
public GovTalkMessageHeaderMessageDetails MessageDetails
{
get
{
return this.messageDetailsField;
}
set
{
this.messageDetailsField = value;
}
}
/// <remarks/>
public GovTalkMessageHeaderSenderDetails SenderDetails
{
get
{
return this.senderDetailsField;
}
set
{
this.senderDetailsField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageHeaderMessageDetails
{
private string classField;
private string qualifierField;
private string functionField;
private string correlationIDField;
private string transformationField;
/// <remarks/>
public string Class
{
get
{
return this.classField;
}
set
{
this.classField = value;
}
}
/// <remarks/>
public string Qualifier
{
get
{
return this.qualifierField;
}
set
{
this.qualifierField = value;
}
}
/// <remarks/>
public string Function
{
get
{
return this.functionField;
}
set
{
this.functionField = value;
}
}
/// <remarks/>
public string CorrelationID
{
get
{
return this.correlationIDField;
}
set
{
this.correlationIDField = value;
}
}
/// <remarks/>
public string Transformation
{
get
{
return this.transformationField;
}
set
{
this.transformationField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageHeaderSenderDetails
{
private GovTalkMessageHeaderSenderDetailsIDAuthentication iDAuthenticationField;
/// <remarks/>
public GovTalkMessageHeaderSenderDetailsIDAuthentication IDAuthentication
{
get
{
return this.iDAuthenticationField;
}
set
{
this.iDAuthenticationField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageHeaderSenderDetailsIDAuthentication
{
private object senderIDField;
private GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthentication authenticationField;
/// <remarks/>
public object SenderID
{
get
{
return this.senderIDField;
}
set
{
this.senderIDField = value;
}
}
/// <remarks/>
public GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthentication Authentication
{
get
{
return this.authenticationField;
}
set
{
this.authenticationField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthentication
{
private object methodField;
private object roleField;
private object valueField;
/// <remarks/>
public object Method
{
get
{
return this.methodField;
}
set
{
this.methodField = value;
}
}
/// <remarks/>
public object Role
{
get
{
return this.roleField;
}
set
{
this.roleField = value;
}
}
/// <remarks/>
public object Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageGovTalkDetails
{
private GovTalkMessageGovTalkDetailsKeys keysField;
/// <remarks/>
public GovTalkMessageGovTalkDetailsKeys Keys
{
get
{
return this.keysField;
}
set
{
this.keysField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageGovTalkDetailsKeys
{
private GovTalkMessageGovTalkDetailsKeysKey keyField;
/// <remarks/>
public GovTalkMessageGovTalkDetailsKeysKey Key
{
get
{
return this.keyField;
}
set
{
this.keyField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageGovTalkDetailsKeysKey
{
private string typeField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageBody
{
private Envelope envelopeField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.w3.org/2003/05/soap-envelope")]
public Envelope Envelope
{
get
{
return this.envelopeField;
}
set
{
this.envelopeField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.w3.org/2003/05/soap-envelope")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.w3.org/2003/05/soap-envelope", IsNullable = false)]
public partial class Envelope
{
private EnvelopeBody bodyField;
/// <remarks/>
public EnvelopeBody Body
{
get
{
return this.bodyField;
}
set
{
this.bodyField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.w3.org/2003/05/soap-envelope")]
public partial class EnvelopeBody
{
private getGenericDrugsResponse getGenericDrugsResponseField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://webservice.sirkb/")]
public getGenericDrugsResponse getGenericDrugsResponse
{
get
{
return this.getGenericDrugsResponseField;
}
set
{
this.getGenericDrugsResponseField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://webservice.sirkb/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://webservice.sirkb/", IsNullable = false)]
public partial class getGenericDrugsResponse
{
private #return returnField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public #return #return
{
get
{
return this.returnField;
}
set
{
this.returnField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.govtalk.gov.uk/CM/envelope", IsNullable = false)]
public partial class #return
{
private returnDRUG[] dRUGField;
private string rETURN_STATUSField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("DRUG")]
public returnDRUG[] DRUG
{
get
{
return this.dRUGField;
}
set
{
this.dRUGField = value;
}
}
/// <remarks/>
public string RETURN_STATUS
{
get
{
return this.rETURN_STATUSField;
}
set
{
this.rETURN_STATUSField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class returnDRUG
{
private string dOSAGEField;
private ushort gENERIC_DRUG_IDField;
private string gENERIC_DRUG_NAMEField;
private string pHARMACEUTICAL_FORMField;
/// <remarks/>
public string DOSAGE
{
get
{
return this.dOSAGEField;
}
set
{
this.dOSAGEField = value;
}
}
/// <remarks/>
public ushort GENERIC_DRUG_ID
{
get
{
return this.gENERIC_DRUG_IDField;
}
set
{
this.gENERIC_DRUG_IDField = value;
}
}
/// <remarks/>
public string GENERIC_DRUG_NAME
{
get
{
return this.gENERIC_DRUG_NAMEField;
}
set
{
this.gENERIC_DRUG_NAMEField = value;
}
}
/// <remarks/>
public string PHARMACEUTICAL_FORM
{
get
{
return this.pHARMACEUTICAL_FORMField;
}
set
{
this.pHARMACEUTICAL_FORMField = value;
}
}
}
I get the following error:
System.InvalidOperationException: 'There is an error in XML document (33, 14).'
Inner Exception
InvalidOperationException: The specified type was not recognized:
name='genericDrug', namespace='http://webservice.sirkb/', at http://www.govtalk.gov.uk/CM/envelope'>.
I have noticed from this thread that if I remove xsi:type="ns2:genericDrug" from the XML file I can deserialize the XML. I can't modify the XML because it is the response I get for the request. It is not a good practice to do a string replace on XML, so I am looking for a better solution.
This might be a duplicate question from this one, but since I am not able to solve the problem I am posting it again because it is difficult to get help in the comment section.
Based on the above question I have tried to change the annotation of public partial class returnDRUG
from
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
to
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.w3.org/2001/XMLSchema-instance", TypeName = "genericDrug")]
but still cant parse the XML.
The parsing code is simple
var deserializer = new XmlSerializer(typeof(GovTalkMessage));
TextReader textReader = new StreamReader("drug.xml"); //saved response in file for simplicity
GovTalkMessage response;
response = (GovTalkMessage)deserializer.Deserialize(textReader);
textReader.Close();
What can I do to deserialize the XML in the GovTalkMessage object?
You need to change the decoration on the returnDRUG class
from this
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class returnDRUG
to this
[System.Xml.Serialization.XmlTypeAttribute(TypeName = "genericDrug", Namespace = "http://webservice.sirkb/")]
public partial class returnDRUG
Specify it's type as "genericDrug", and the crucial bit, correct it's namespace to "http://webservice.sirkb/"
I've just used you code and managed to de-serialize using this change.
The explanation is that if you take a look at the definition of DRUG you can see that it's type is defined as "genericDRUG" in the namespace alias "ns2"
<DRUG xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns2:genericDrug">
if you look at the definition of the ns2 alias you can see that it's "http://webservice.sirkb/"
<ns2:getGenericDrugsResponse xmlns:ns2="http://webservice.sirkb/">
Some addition to prevent default values for DRUG objects
Every property of the returnDrug class should have the namespace http://www.govtalk.gov.uk/CM/envelope.
The complete class should have the following form:
[System.Xml.Serialization.XmlTypeAttribute(TypeName = "genericDrug", Namespace = "http://webservice.sirkb/")]
public partial class returnDRUG
{
private string dOSAGEField;
private ushort gENERIC_DRUG_IDField;
private string gENERIC_DRUG_NAMEField;
private string pHARMACEUTICAL_FORMField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public string DOSAGE
{
get
{
return this.dOSAGEField;
}
set
{
this.dOSAGEField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public ushort GENERIC_DRUG_ID
{
get
{
return this.gENERIC_DRUG_IDField;
}
set
{
this.gENERIC_DRUG_IDField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public string GENERIC_DRUG_NAME
{
get
{
return this.gENERIC_DRUG_NAMEField;
}
set
{
this.gENERIC_DRUG_NAMEField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public string PHARMACEUTICAL_FORM
{
get
{
return this.pHARMACEUTICAL_FORMField;
}
set
{
this.pHARMACEUTICAL_FORMField = value;
}
}
}
I'm having trouble de-serializing an XML document.
<rules version="61">
<emie>
<domain exclude="false">facebook.com</domain>
<domain exclude="false">google.com</domain>
<domain exclude="false">bbc.co.uk</domain>
</emie>
<docMode>
<domain docMode="7">outlook.com</domain>
<domain docMode="7">yahoo.com</domain>
</docMode>
</rules>
I've copied and pasted into visual studio - using the Paste XML as class and that's created the following class
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class rules
{
private rulesDomain[] emieField;
private rulesDomain1[] docModeField;
private byte versionField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("domain", IsNullable = false)]
public rulesDomain[] emie
{
get
{
return this.emieField;
}
set
{
this.emieField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("domain", IsNullable = false)]
public rulesDomain1[] docMode
{
get
{
return this.docModeField;
}
set
{
this.docModeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public byte version
{
get
{
return this.versionField;
}
set
{
this.versionField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class rulesDomain
{
private bool excludeField;
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool exclude
{
get
{
return this.excludeField;
}
set
{
this.excludeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class rulesDomain1
{
private string docModeField;
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string docMode
{
get
{
return this.docModeField;
}
set
{
this.docModeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
I then run the following code to deserialise
XmlSerializer mySerializer = new XmlSerializer(typeof(XmlSerializer));
Classes.rules r;
using (StreamReader reader = new StreamReader(#"file.xml"))
{
r = (Classes.rules)mySerializer.Deserialize(reader);
}
It's errors on the line r =... {" was not expected."}
I'm pretty certain the error lies in the class and the declarations at the top but I haven't been able to change it so it works, could anyone help?
Change
XmlSerializer mySerializer = new XmlSerializer(typeof(XmlSerializer));
to
XmlSerializer mySerializer = new XmlSerializer(typeof(Classes.rules));
Its parameter is type of the object that this XmlSerializer can serialize.
After Posting to a certain URL, I get the following Response:
<?xml version="1.0" encoding="utf-8" ?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<soapenv:Fault>
<faultcode>123</faultcode>
<faultstring>Lorem Ipsum</faultstring>
<detail>
<ns1:Service xmlns:ns1="http://www.bla.org/">
<messageId>321</messageId>
<text>Test Text</text>
<variables>19</variables>
<variables>20</variables>
</ns1:Service>
</detail>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>
I want to Parse it and use the Values
I tried to Parse the XmlString to the following Class:
public class ClassXml
{
/// <remarks/>
[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;
/// <remarks/>
public EnvelopeBody Body
{
get
{
return this.bodyField;
}
set
{
this.bodyField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public partial class EnvelopeBody
{
private EnvelopeBodyFault faultField;
/// <remarks/>
public EnvelopeBodyFault Fault
{
get
{
return this.faultField;
}
set
{
this.faultField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public partial class EnvelopeBodyFault
{
private string faultcodeField;
private string faultstringField;
private detail detailField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "")]
public string faultcode
{
get
{
return this.faultcodeField;
}
set
{
this.faultcodeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "")]
public string faultstring
{
get
{
return this.faultstringField;
}
set
{
this.faultstringField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "")]
public detail detail
{
get
{
return this.detailField;
}
set
{
this.detailField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class detail
{
private Service serviceField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.bla.org/")]
public Service Service
{
get
{
return this.serviceField;
}
set
{
this.serviceField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.bla.org/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.bla.org/", IsNullable = false)]
public partial class Service
{
private string messageIdField;
private string textField;
private ulong[] variablesField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "")]
public string messageId
{
get
{
return this.messageIdField;
}
set
{
this.messageIdField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "")]
public string text
{
get
{
return this.textField;
}
set
{
this.textField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("variables", Namespace = "")]
public ulong[] variables
{
get
{
return this.variablesField;
}
set
{
this.variablesField = value;
}
}
}
}
But I got the error:
Exception Occured while trying to parse XML String
<Envelope xmlns='http://schemas.xmlsoap.org/soap/envelope/'> was not expected.
Apparently I can't parse an XML with namespaces like I parse a normal XML
How can I parse this one and get the values?
Any help would be appreciated
I am trying to retrieve data from Zoho API and then I want to Deserialize a returned data in an object.
The XML structure:
<response uri="/crm/private/xml/Potentials/getSearchRecords">
<result>
<Potentials>
<row no="1">
<FL val="POTENTIALID">0000000000000</FL>
<FL val="SMOWNERID">000000000000</FL>
.......
</row>
<row no="2">
.......
</row>
</Potentials>
</result>
</response>
And here what I tried but didn't succeed.
[Serializable()]
public class ZohoXML
{
public ZohoXML() { }
[XmlElement("POTENTIALID")]
public string POTENTIALID { get; set; }
........
}
[XmlRoot("response")]
public class Response
{
[XmlElement("result")]
public Result[] ResultList { get; set; }
}
public class Result
{
[XmlArray("Potentials"), XmlArrayItem("row")]
public Row[] RowList { get; set; }
}
[XmlRoot("row")]
public class Row
{
[XmlArray("Potentials")]
[XmlArrayItem("row", typeof(ZohoXML))]
public ZohoXML[] ZohoXML { get; set; }
}
And this is how I deserialize:
Response ZohoXMLCollection = null;
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Response));
StreamReader reader = new StreamReader(strFile);
ZohoXMLCollection = (Response)serializer.Deserialize(reader);
reader.Close();
Can anybody please help on identifying an issue in the code ?
If you are using a newer version of VS you can use Edit > Paste Special > Paste XML as Classes in the edit menu. Assuming your XML structure is correct this will give you:
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class response
{
private responseResult resultField;
private string uriField;
/// <remarks/>
public responseResult result
{
get
{
return this.resultField;
}
set
{
this.resultField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string uri
{
get
{
return this.uriField;
}
set
{
this.uriField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class responseResult
{
private responseResultRow[] potentialsField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("row", IsNullable = false)]
public responseResultRow[] Potentials
{
get
{
return this.potentialsField;
}
set
{
this.potentialsField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class responseResultRow
{
private responseResultRowFL[] flField;
private byte noField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("FL")]
public responseResultRowFL[] FL
{
get
{
return this.flField;
}
set
{
this.flField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public byte no
{
get
{
return this.noField;
}
set
{
this.noField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class responseResultRowFL
{
private string valField;
private byte valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string val
{
get
{
return this.valField;
}
set
{
this.valField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public byte Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
You will want to clean up the names but for now this is fine.
Then your de-serialization will look like this:
XmlSerializer serializer = new XmlSerializer(typeof(response));
response res = new response();
using (StreamReader reader = new StreamReader(fileLocation))
{
res = serializer.Deserialize(reader) as response;
}
Note that StreamReader implements the IDisposable interface so should be used within a using block to ensure automatic disposable of resources.