Code for specific XML data [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need to generate this xml from a c# code however i m lost in xmlwriter provided multiple writers.. Can anyone who got expertise in xml can help me out for writing C# code to produce this below xml:
<?xml version="1.0" encoding="utf-16" ?>
<Request xmlns="http://www.ABC.com/submit" xmlns:l="http://www.ABC.com/link" l:source="SRC" l:date="2014-03-05">
<MyData l:identifier="PRAV" l:value="151.19448366182007269092408546">
<DATA1 l:value="0.151328110447635" />
<DATA2 l:value="0.6461191930062688087600920641" />
<DATA3 l:value="0.144793773777417" />
</MyData>
</Request>

Use the Paste Special feature of Visual Studio.
With this you can copy your XML structure (provided it is valid which currently it isn't).
Select:
Edit
Paste Special
Paste XML as Classes
This will give you a class representing your XML:
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.ABC.com/submit")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.ABC.com/submit", IsNullable = false)]
public partial class Request
{
private RequestMyData myDataField;
private string sourceField;
private System.DateTime dateField;
/// <remarks/>
public RequestMyData MyData
{
get
{
return this.myDataField;
}
set
{
this.myDataField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified, Namespace = "http://www.ABC.com/link")]
public string source
{
get
{
return this.sourceField;
}
set
{
this.sourceField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified, Namespace = "http://www.ABC.com/link", DataType = "date")]
public System.DateTime date
{
get
{
return this.dateField;
}
set
{
this.dateField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.ABC.com/submit")]
public partial class RequestMyData
{
private RequestMyDataDATA1 dATA1Field;
private RequestMyDataDATA2 dATA2Field;
private RequestMyDataDATA3 dATA3Field;
private string identifierField;
private decimal valueField;
/// <remarks/>
public RequestMyDataDATA1 DATA1
{
get
{
return this.dATA1Field;
}
set
{
this.dATA1Field = value;
}
}
/// <remarks/>
public RequestMyDataDATA2 DATA2
{
get
{
return this.dATA2Field;
}
set
{
this.dATA2Field = value;
}
}
/// <remarks/>
public RequestMyDataDATA3 DATA3
{
get
{
return this.dATA3Field;
}
set
{
this.dATA3Field = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified, Namespace = "http://www.ABC.com/link")]
public string identifier
{
get
{
return this.identifierField;
}
set
{
this.identifierField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified, Namespace = "http://www.ABC.com/link")]
public decimal value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.ABC.com/submit")]
public partial class RequestMyDataDATA1
{
private decimal valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified, Namespace = "http://www.ABC.com/link")]
public decimal value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.ABC.com/submit")]
public partial class RequestMyDataDATA2
{
private decimal valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified, Namespace = "http://www.ABC.com/link")]
public decimal value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.ABC.com/submit")]
public partial class RequestMyDataDATA3
{
private decimal valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified, Namespace = "http://www.ABC.com/link")]
public decimal value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}

If you write your classes as DataContracts and assigns XML attributes to the DataMembers you should be able to get what you need.
[DataContract]
public class Request
{
[DataMember, XmlAttribute]
public string Source { get; set; }
[DataMember]
public MyData MyData { get; set; }
}
[DataContract]
public class MyData
{
[DataMember, XmlAttribute]
public string Identifier { get; set; }
[DataMember, XmlAttribute]
public double Value { get; set; }
[DataMember]
public List<Data> Datum { get; set; }
}
[DataContract]
public class Data
{
[DataMember, XmlAttribute]
public double Value { get; set; }
}
and to test
var listOfData = new List<Data> {new Data {Value = 0.15}, new Data {Value = 0.64}};
var myData = new MyData {Identifier = "PRAV", Value = 151.194, Datum = listOfData};
var request = new Request {MyData = myData, Source = "SRC"};
XmlSerializer ser = new XmlSerializer(typeof(Request));
StringWriter sw = new StringWriter();
ser.Serialize(sw, request);
Console.WriteLine(sw.ToString());
Thiis will result in
<?xml version="1.0" encoding="utf-16"?>
<Request
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http:/ /www.w3.org/2001/XMLSchema" Source="SRC">
<MyData Identifier="PRAV" Value="151.194">
<Datum>
<Data Value="0.15" />
<Data Value="0.64" />
</Datum>
</MyData>
</Request>

You can use XDocument to create XML file from C# :
using System.Xml.Linq;
var doc = new XDocument(new XDeclaration("1.0", "utf-16", ""));
XNamespace ns = "http://www.ABC.com/submit";
XNamespace l = "http://www.ABC.com/link";
//<Request>
doc.Add(new XElement(ns+"Request",
//xmlns="http://www.ABC.com/submit"
new XAttribute("xmlns", "http://www.ABC.com/submit"),
//xmlns:l="http://www.ABC.com/link"
new XAttribute(XNamespace.Xmlns + "l", "http://www.ABC.com/link"),
//l:source="SRC"
new XAttribute(l+"source", "SRC"),
//l:date="2014-03-05"
new XAttribute(l + "date", "2014-03-05"),
//<MyData>
new XElement(ns+"MyData",
//l:identifier="PRAV"
new XAttribute(l+"identifier", "PRAV"),
//l:value="151.19448366182007269092408546"
new XAttribute(l + "value", "151.19448366182007269092408546"),
//<DATA1>
new XElement(ns+"DATA1",
//l:value="0.151328110447635"
new XAttribute(l + "value", "0.151328110447635")),
//<DATA2>
new XElement(ns+"DATA2",
//l:value="0.6461191930062688087600920641"
new XAttribute(l + "value", "0.6461191930062688087600920641")),
//<DATA3>
new XElement(ns+"DATA3",
//l:value="0.144793773777417"
new XAttribute(l + "value", "0.144793773777417")))));
doc.Save("xml_name.xml");

Related

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.

C# can't deserialize XML containing xsi:type

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

XML Deserialization is not working

I'm trying to deserialize the below XML but the process seems not to be working...
Here's what I get when I display the values in a PropertyGrid control after deserializing the XML:
As you can see, the elements under Header has no values.
Can you please help to check what's wrong with the codes?
Message class:
namespace MyProject
{
[XmlRoot(ElementName="Header")]
public class Header {
[XmlElement(ElementName="Sender")]
public string Sender { get; set; }
[XmlElement(ElementName="Receiver")]
public string Receiver { get; set; }
[XmlElement(ElementName="MessageID")]
public string MessageID { get; set; }
[XmlElement(ElementName="CreationDateTime")]
public string CreationDateTime { get; set; }
[XmlAttribute(AttributeName="version")]
public string Version { get; set; }
}
[XmlRoot(ElementName="Message", Namespace="http://example.com")]
public class Message {
private Header _header = new Header();
[XmlElement(ElementName="Header")]
[TypeConverter(typeof(ConverterExpandableObject))]
public Header Header
{
get { return _header; }
set { _header = value; }
}
[XmlAttribute(AttributeName="ns", Namespace="http://www.w3.org/2000/xmlns/")]
public string Ns { get; set; }
}
}
Method to deserialize the XML:
void DeserializeMessage()
{
string messageString = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\Message.xml";
if (File.Exists(messageString))
{
XmlSerializer serializer = new XmlSerializer(typeof(Message));
StreamReader reader = new StreamReader(messageString);
Message m = (Message)serializer.Deserialize(reader);
reader.Close();
propertyGrid1.SelectedObject = m;
}
}
and the XML itself:
<?xml version="1.0" encoding="UTF-8"?>
<ns:Message xmlns:ns="http://example.com">
<Header version="1.0">
<Sender>3015207400109</Sender>
<Receiver>8711200999903</Receiver>
<MessageID>000D2613F64AC021ED783C084735EC78E53</MessageID>
<CreationDateTime>2017-03-21T08:00:47Z</CreationDateTime>
</Header>
</ns:Message>
change you classes like below and it will work.
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://example.com")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://example.com", IsNullable = false)]
public partial class Message
{
private Header headerField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "")]
public Header Header
{
get
{
return this.headerField;
}
set
{
this.headerField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Header
{
private ulong senderField;
private ulong receiverField;
private string messageIDField;
private System.DateTime creationDateTimeField;
private decimal versionField;
/// <remarks/>
public ulong Sender
{
get
{
return this.senderField;
}
set
{
this.senderField = value;
}
}
/// <remarks/>
public ulong Receiver
{
get
{
return this.receiverField;
}
set
{
this.receiverField = value;
}
}
/// <remarks/>
public string MessageID
{
get
{
return this.messageIDField;
}
set
{
this.messageIDField = value;
}
}
/// <remarks/>
public System.DateTime CreationDateTime
{
get
{
return this.creationDateTimeField;
}
set
{
this.creationDateTimeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal version
{
get
{
return this.versionField;
}
set
{
this.versionField = value;
}
}
}
OUTPUT

Parse XML with Namespaces C#

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

Deserialize nested level XML

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.

Categories

Resources