Using XmlSerializer to create a non-standard element - c#

I'm trying to create an XML output file to import into another program. The example XML file I was given looks like this:
<SalesOrder>
<OrderHeader>
<BillTo>
<EntityID>1234</EntityID>
</BillTo>
</OrderHeader>
<LineItemList>
<OrderLineComment>
<LineItemID>1</LineItemID>
</OrderLineComment>
<LineItem>
...
</LineItem>
<LineItem>
...
</LineItem>
<LineItem>
...
</LineItem>
...
</LineItemList>
</SalesOrder>
I have a C# project that is able to output this type of file using an XmlSerializer with the exception of this part:
<LineItemList>
<OrderLineComment>
<LineItemID>1</LineItemID>
</OrderLineComment>
The LineItemList section is simply a list of LineItems, but at the beginning of the LineItemList there is tacked this different element OrderLineComment.
If I represent this as an array of LineItems, then it looks the same except it's missing the OrderLineComment. If I represent this as a new object LineItemList containing an OrderLineComment and an array of LineItems, I get this:
<LineItemList>
<OrderLineComment>
<LineItemID>1</LineItemID>
</OrderLineComment>
<LineItems>
<LineItem>
...
</LineItem>
...
</LineItems>
Which has what I want, except it wraps all the LineItems with the <LineItems> tag, which isn't what I want either.
So what I'm wondering is:
Is there a way to do this via XmlSerializer? If so, how?
If there isn't, and I have to rewrite the code to use something other than XmlSerializer, what would be the best way to do this and why?
Thanks in advance.

You can make a OrderLineComment and LineItem derive from a common base class :
public abstract class LineItemBase
{
...
}
public class LineItem : LineItemBase
{
...
}
public class OrderLineComment : LineItemBase
{
...
}
Then declare the LineItemList property as a collection of LineItemBase objects, and use the XmlArrayItem attribute to specify which types can be included in the collection:
[XmlArrayItem(typeof(LineItem))]
[XmlArrayItem(typeof(OrderLineComment))]
public List<LineItemBase> LineItemList { get; set; }
This should achieve what you want

You can always implement IXmlSerializable interface on your type. It allows serialization of any complexity and it works with XmlSerializer.
Edit:
Here is the example of generated code if you want to achieve it with standard attributes. I created xsd from your xml and generated the code with XSD.exe.
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[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 SalesOrder {
private OrderHeader orderHeaderField;
private LineItemList lineItemListField;
/// <remarks/>
public OrderHeader OrderHeader {
get {
return this.orderHeaderField;
}
set {
this.orderHeaderField = value;
}
}
/// <remarks/>
public LineItemList LineItemList {
get {
return this.lineItemListField;
}
set {
this.lineItemListField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[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 OrderHeader {
private BillTo billToField;
/// <remarks/>
public BillTo BillTo {
get {
return this.billToField;
}
set {
this.billToField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[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 BillTo {
private short entityIDField;
/// <remarks/>
public short EntityID {
get {
return this.entityIDField;
}
set {
this.entityIDField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[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 LineItemList {
private OrderLineComment orderLineCommentField;
private string[] lineItemField;
/// <remarks/>
public OrderLineComment OrderLineComment {
get {
return this.orderLineCommentField;
}
set {
this.orderLineCommentField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("LineItem")]
public string[] LineItem {
get {
return this.lineItemField;
}
set {
this.lineItemField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[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 OrderLineComment {
private sbyte lineItemIDField;
/// <remarks/>
public sbyte LineItemID {
get {
return this.lineItemIDField;
}
set {
this.lineItemIDField = value;
}
}
}

Related

Deserializing XML attributes from the same Xml element c#

I want to deseralize the following XML in C#
<Configuration>
<Parameters>
<Parameter AttrName1 = "AttrValue1"/>
<Parameter AttrName2 = "AttrValue2"/>
<Parameter AttrName3 = "AttrValue3"/>
</Parameters>
</Configuration>
I am having trouble because Attributes names and values are all differents for the same value.
Thank you so much.
You can use these classes to serialize/deserialize your xml. Note this is a feature in VS: Paste XML as Classes
// 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 Configuration
{
private ConfigurationParameter[] parametersField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)]
public ConfigurationParameter[] Parameters
{
get
{
return this.parametersField;
}
set
{
this.parametersField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class ConfigurationParameter
{
private string attrName1Field;
private string attrName2Field;
private string attrName3Field;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string AttrName1
{
get
{
return this.attrName1Field;
}
set
{
this.attrName1Field = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string AttrName2
{
get
{
return this.attrName2Field;
}
set
{
this.attrName2Field = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string AttrName3
{
get
{
return this.attrName3Field;
}
set
{
this.attrName3Field = value;
}
}
}

Weird error when i try to Deserialize a xml string to a .net List Object

I have asked this question twice already but not one have given me an answer that actually works so i will try again. I have this xml:
<?xml version="1.0" encoding="UTF-8"?>
<people type="array">
<person>
<first-name>Mark</first-name>
<last-name>Zette</last-name>
<e-mail>mark.zette#hotmail.com</e-mail>
</person>
<person>
<first-name>Sara</first-name>
<last-name>Brobro</last-name>
<e-mail>brobro#hotmail.com</e-mail>
</person>
<person>
<first-name>Rob</first-name>
<last-name>Sel</last-name>
<e-mail>rob.selhotmail.com</e-mail>
</person>
<person>
<first-name>Aden</first-name>
<last-name>Snor</last-name>
<e-mail>aden.Snor#hotmail.com</e-mail>
</person>
</people>
So I want to turn this xml into a list of this object:
//------------------------------------------------------------------------------
// <auto-generated>
// Denna kod har genererats av ett verktyg.
// Körtidsversion:4.0.30319.42000
//
// Ändringar i denna fil kan orsaka fel och kommer att förloras om
// koden återgenereras.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=4.6.1055.0.
//
/// <remarks/>
[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 people {
private peoplePerson[] personField;
private string typeField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("person", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public peoplePerson[] person {
get {
return this.personField;
}
set {
this.personField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
}
/// <remarks/>
[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 peoplePerson {
private string firstnameField;
private string lastnameField;
private string emailField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("first-name", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string firstname {
get {
return this.firstnameField;
}
set {
this.firstnameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("last-name", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string lastname {
get {
return this.lastnameField;
}
set {
this.lastnameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("e-mail", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string email {
get {
return this.emailField;
}
set {
this.emailField = value;
}
}
}
/// <remarks/>
[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 NewDataSet {
private people[] itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("people")]
public people[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
This class is autogenerated. Throug running "xsd.exe peoples.xml" and then "xsd.exe /c peoples.xsd" in the visual studio command prompt.
Now this is my code plus error: (And for those that don't know Swedish after additional information it says "There is something wrong with your XML-document(3,2)")
string xmlPath = Path.Combine(HostingEnvironment.MapPath("~/App_Data"), "peoples.xml");
StreamReader sr = new StreamReader(xmlPath);
string xml = sr.ReadToEnd(); //i suspect the problem might appear here maybe. When i convert the xml to string it might
//happend something to the xmlstring that the deserialize
//method cant read. But i dont know just guessing.
XmlSerializer serializer = new XmlSerializer(typeof(List<people>));
using (TextReader reader = new StringReader(xml))
{
List<people> person = (List<people>)serializer.Deserialize(reader);
}
return View();
Your XML file doesn't represent a List<people> - it contains a single people; that's what the root element is. That then contains sub-elements. You can get those easily though:
XmlSerializer serializer = new XmlSerializer(typeof(people));
using (TextReader reader = new StringReader(json))
{
people person = (people) serializer.Deserialize(reader);
List<peoplePerson> list = person.person.ToList();
Console.WriteLine(list.Count); // Prints 4
}
(I'd strongly advise you to rewrite the autogenerated code following .NET naming conventions and using automatically implemented properties though.)

Generate C# class from XSD sitemap with images

Could somebody help me generate C# class from XSD(sitemap with images)?
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
<url>
<loc>http://example.com/sample.html</loc>
<image:image>
<image:loc>http://example.com/image.jpg</image:loc>
</image:image>
<image:image>
<image:loc>http://example.com/photo.jpg</image:loc>
</image:image>
</url>
</urlset>
Here is my classes that were generated by xsd.exe tool:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true,
Namespace = "http://www.sitemaps.org/schemas/sitemap/0.9")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.sitemaps.org/schemas/sitemap/0.9",
IsNullable = false)]
public partial class urlset
{
private System.Xml.XmlElement[] anyField;
private List<tUrl> urlField;
/// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.XmlElement[] Any
{
get { return this.anyField; }
set { this.anyField = value; }
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("url")]
public List<tUrl> url
{
get { return this.urlField; }
set { this.urlField = value; }
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.sitemaps.org/schemas/sitemap/0.9")]
public partial class tUrl
{
private string locField;
private string lastmodField;
private tChangeFreq changefreqField;
private bool changefreqFieldSpecified;
private decimal priorityField;
private bool priorityFieldSpecified;
private System.Xml.XmlElement[] anyField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType = "anyURI")]
public string loc
{
get { return this.locField; }
set { this.locField = value; }
}
/// <remarks/>
public string lastmod
{
get { return this.lastmodField; }
set { this.lastmodField = value; }
}
/// <remarks/>
public tChangeFreq changefreq
{
get { return this.changefreqField; }
set { this.changefreqField = value; }
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool changefreqSpecified
{
get { return this.changefreqFieldSpecified; }
set { this.changefreqFieldSpecified = value; }
}
/// <remarks/>
public decimal priority
{
get { return this.priorityField; }
set { this.priorityField = value; }
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool prioritySpecified
{
get { return this.priorityFieldSpecified; }
set { this.priorityFieldSpecified = value; }
}
/// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.XmlElement[] Any
{
get { return this.anyField; }
set { this.anyField = value; }
}
[System.Xml.Serialization.XmlElementAttribute(ElementName = "image", Type = typeof(image))]
public List<image> Images { get; set; }
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.sitemaps.org/schemas/sitemap/0.9")]
public enum tChangeFreq
{
/// <remarks/>
always,
/// <remarks/>
hourly,
/// <remarks/>
daily,
/// <remarks/>
weekly,
/// <remarks/>
monthly,
/// <remarks/>
yearly,
/// <remarks/>
never,
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true,
Namespace = "http://www.google.com/schemas/sitemap-image/1.1")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.google.com/schemas/sitemap-image/1.1",
IsNullable = false)]
public partial class image
{
private string locField;
private string captionField;
private string geo_locationField;
private string titleField;
private string licenseField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(ElementName = "loc", DataType = "anyURI")]
public string loc
{
get { return this.locField; }
set { this.locField = value; }
}
/// <remarks/>
public string caption
{
get { return this.captionField; }
set { this.captionField = value; }
}
/// <remarks/>
public string geo_location
{
get { return this.geo_locationField; }
set { this.geo_locationField = value; }
}
/// <remarks/>
public string title
{
get { return this.titleField; }
set { this.titleField = value; }
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType = "anyURI")]
public string license
{
get { return this.licenseField; }
set { this.licenseField = value; }
}
}
But I have problem with prefix 'image:', I could not sort out how to add this prefix to serialized xml. If I modify Element name by adding semicolon, then it do escape 'image_x003A_image'
I also used the xsd.exe tool and had the same issue. I resolved it as follows:
In the urlset class, add the following [XmlNamespaceDeclarations] property and create a constructor that adds the "image" xml namespace:
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces xmlns = new XmlSerializerNamespaces();
public urlset()
{
xmlns.Add("image", "http://www.google.com/schemas/sitemap-image/1.1");
}
In my case I only needed a single image, so I added the following attribute to my image property in tUrl
[XmlElement(Namespace = "http://www.google.com/schemas/sitemap-image/1.1")]
public image image
{
get
{
return this.imageField;
}
set
{
this.imageField = value;
}
}
This then added the "image:" prefix to all my image elements. You should be able to do something similar for you image list to associate it with the namespace you created above.
This post seems a little old, but hope this helps someone experiencing similar headaches trying to utilize the image sitemap schema extension.

How to add XML attributes in XML Serialization C#

Hi am having some problems in XML serialization of XML attributes, following are some details of class file generated from XSD.
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://tempuri.org/UpdatePolicy.xsd")]
public partial class policyClasses {
private policyClassesClass[] classField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("class")]
public policyClassesClass[] #class {
get {
return this.classField;
}
set {
this.classField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://tempuri.org/UpdatePolicy.xsd")]
public partial class policyClassesClass {
private string company_idField;
private string deductable_rateField;
private string max_limitField;
private string class_nameField;
private string class_numberField;
private policyClassesClassCchi_class_number cchi_class_numberField;
private policyClassesClassAction_type action_typeField;
private bool action_typeFieldSpecified;
/// <remarks/>
public string company_id {
get {
return this.company_idField;
}
set {
this.company_idField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="positiveInteger")]
public string deductable_rate {
get {
return this.deductable_rateField;
}
set {
this.deductable_rateField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="positiveInteger")]
public string max_limit {
get {
return this.max_limitField;
}
set {
this.max_limitField = value;
}
}
/// <remarks/>
public string class_name {
get {
return this.class_nameField;
}
set {
this.class_nameField = value;
}
}
/// <remarks/>
public string class_number {
get {
return this.class_numberField;
}
set {
this.class_numberField = value;
}
}
/// <remarks/>
public policyClassesClassCchi_class_number cchi_class_number {
get {
return this.cchi_class_numberField;
}
set {
this.cchi_class_numberField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public policyClassesClassAction_type action_type {
get {
return this.action_typeField;
}
set {
this.action_typeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool action_typeSpecified {
get {
return this.action_typeFieldSpecified;
}
set {
this.action_typeFieldSpecified = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://tempuri.org/UpdatePolicy.xsd")]
public enum policyClassesClassCchi_class_number {
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("1")]
Item1,
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("2")]
Item2,
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("3")]
Item3,
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("4")]
Item4,
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://tempuri.org/UpdatePolicy.xsd")]
public enum policyClassesClassAction_type {
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("10")]
Item10,
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("1")]
Item1,
I managed to generate XML based on this class by serialization, but not having any idea to add the XML attribute to the XML generated, i supposed to get an output as below.
<classes>
<class action_type="10">
<company_id>999</company_id>
<deductable_rate>20</deductable_rate>
<max_limit>800</max_limit>
<class_name>Class A</class_name>
<class_number>1</class_number>
<cchi_class_number>2</cchi_class_number>
</class>
how to add the attribute to the element <class action_type = "10">
from /// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public policyClassesClassAction_type action_type {
get {
return this.action_typeField;
}
set {
this.action_typeField = value;
}
}
Please somebody help me on this to manage my deadlines, also tell me if anything is not clear for the valuable responses
Joe
Notice that the generated class is marked partial.
Add another class right next to the generated one in your project and give it a similar name, such as GeneratedClasses.addon.cs. Add this in your new file:
public partial class policyClasses {
[System.Xml.Serialization.XmlAttribute]
public policyClassesClassAction_type action_type { get;set;}
}

How to Deserialize this Xml file?

I have this Xml file, and I need to Deserialize it back to a class. The problem is: what is the right structure/design of this class considering that the count of the Xml element (RowInfo) is not constant?
The Xml File:
<?xml version="1.0"?>
<SomeObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<Layers>
<Layer Id="0">
<RowInfo>1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1</RowInfo>
<RowInfo>1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1</RowInfo>
<RowInfo>1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1</RowInfo>
<RowInfo>1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1</RowInfo>
<RowInfo>1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1</RowInfo>
<RowInfo>1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1</RowInfo>
<RowInfo>1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1</RowInfo>
<RowInfo>1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1</RowInfo>
<RowInfo>1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1</RowInfo>
<RowInfo>1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1</RowInfo>
<RowInfo>1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1</RowInfo>
<RowInfo>1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1</RowInfo>
<RowInfo>1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1</RowInfo>
<RowInfo>1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1</RowInfo>
<RowInfo>1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1</RowInfo>
<RowInfo>1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1</RowInfo>
<RowInfo>1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1</RowInfo>
<RowInfo>1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1</RowInfo>
<RowInfo>1,1,1,0,0,1,1,1,1,1,1,1,1,1,0,0,1,0,0,1</RowInfo>
<RowInfo>1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1</RowInfo>
</Layer>
</Layers>
</SomeObject>
Appreciate your help.
Thanks.
Edit1:also considering that (Layers) may contains more than one layer.
Something like the following - names will need to be changed to protect the innocent:
Class structure after comment
public class SomeObject
{
public List<Layer> Layers {get;set;}
}
public class Layer
{
public int Id {get;set;}
public List<RowInfo> RowInfos {get;set;}
}
public class RowInfo
{
public List<Row> Rows {get;set;}
}
public class Row
{
public int RowData {get;set;}
}
This should work as you want:
public class SomeObject
{
public List<Layer> Layers { get; set; }
}
public class Layer
{
[XmlAttribute]
public int Id { get; set; }
[XmlElement("RowInfo")]
public List<RowInfo> RowInfos { get; set; }
}
public class RowInfo
{
[XmlText]
public string Info { get; set; } // you'll need to parse the list of ints manually
}
The only difference is the encoding but you should be able to work around it.
If the count of RowInfo is not constant, use a List in your class.
XmlSerializer serializer = new XmlSerializer(typeof(SomeObject));
you can use XmlSerializer with the following code and call Deserialize :)
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.4952
//
// 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=2.0.50727.3038.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[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 SomeObject {
private SomeObjectLayers layersField;
/// <remarks/>
public SomeObjectLayers Layers {
get {
return this.layersField;
}
set {
this.layersField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class SomeObjectLayers {
private SomeObjectLayersLayer layerField;
/// <remarks/>
public SomeObjectLayersLayer Layer {
get {
return this.layerField;
}
set {
this.layerField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class SomeObjectLayersLayer {
private decimal[] rowInfoField;
private int idField;
private bool idFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("RowInfo")]
public decimal[] RowInfo {
get {
return this.rowInfoField;
}
set {
this.rowInfoField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public int Id {
get {
return this.idField;
}
set {
this.idField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool IdSpecified {
get {
return this.idFieldSpecified;
}
set {
this.idFieldSpecified = value;
}
}
}
I would say use LINQ-to-Xml. Have a constructor on your object that can take an xlement then do
Something along the lines of
public class YourObject()
{
public IEnumerable<Layer> Layers { get; set; }
public int Id { get; set; }
public YourObj(XElement x)
{
this.Id = int.Parse(x.Attribute("Id").ToString());
this.Layers = from layer in x.Elements("Layer")
select new Layer(layer);
}
}
var objs = (from c in XElement.Load("your.xml").Elements("layer")
select new YourObject(c)).ToList() ;
Checkout a tool called XSD.exe it come with visual studio and will allow you to generate code form an xml file.
You should see it on the program files menu next to visual studio.

Categories