Can someone please help me, I have this xml snippet
<?xml version="1.0" encoding="utf-8" ?>
<EmailConfiguration>
<DataBoxID>123</DataBoxID>
<DefaultSendToAddressCollection>
<EmailAddress>email#whereEver.com</EmailAddress>
</DefaultSendToAddressCollection>
</EmailConfiguration>
I want to create a corressponding c# class from this. Before you say - "Just use xsd.exe", the output from Xsd cannot be serialized and deserialized correct, because it generates the class using partial classes.
Please can you tell me how to create this class.... here is the approach I took, but it doesn't work.
public class EmailConfiguration
{
private string dataBoxID;
public string DataBoxID
{
get { return dataBoxID; }
set { dataBoxID = value; }
}
private DefaultSendToAddressCollectionClass defaultSendToAddressCollection;
public DefaultSendToAddressCollectionClass DefaultSendToAddressCollection
{
get { return defaultSendToAddressCollection; }
set { defaultSendToAddressCollection = value; }
}
}
And here is the class declaration for the subclass
public class DefaultSendToAddressCollectionClass
{
private string[] emailAddress;
public string[] EmailAddress
{
get { return emailAddress; }
set { emailAddress = value; }
}
}
Did you use VS2008's XSD?
Here's the output I got:
c:>xsd email.xml
Writing file 'c:\email.xsd'
c:>xsd email.xsd /c /edb
Writing file 'c:\email.cs'
Generates serializable output:
[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 EmailConfiguration : object, System.ComponentModel.INotifyPropertyChanged {
private string dataBoxIDField;
private EmailConfigurationDefaultSendToAddressCollection[] defaultSendToAddressCollectionField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string DataBoxID {
get {
return this.dataBoxIDField;
}
set {
this.dataBoxIDField = value;
this.RaisePropertyChanged("DataBoxID");
}
}
You have two possibilities.
Method 1. XSD tool
Suppose that you have your XML file in this location C:\path\to\xml\file.xml
Open Developer Command Prompt
You can find it in Start Menu > Programs > Microsoft Visual Studio 2012 > Visual Studio Tools
Or if you have Windows 8 can just start typing Developer Command Prompt in Start screen
Change location to your XML file directory by typing cd /D "C:\path\to\xml"
Create XSD file from your xml file by typing xsd file.xml
Create C# classes by typing xsd /c file.xsd
And that's it! You have generated C# classes from xml file in C:\path\to\xml\file.cs
Method 2 - Paste special
Required Visual Studio 2012+
Copy content of your XML file to clipboard
Add to your solution new, empty class file (Shift+Alt+C)
Open that file and in menu click Edit > Paste special > Paste XML As Classes
And that's it!
Usage
Usage is very simple with this helper class:
using System;
using System.IO;
using System.Web.Script.Serialization; // Add reference: System.Web.Extensions
using System.Xml;
using System.Xml.Serialization;
namespace Helpers
{
internal static class ParseHelpers
{
private static JavaScriptSerializer json;
private static JavaScriptSerializer JSON { get { return json ?? (json = new JavaScriptSerializer()); } }
public static Stream ToStream(this string #this)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(#this);
writer.Flush();
stream.Position = 0;
return stream;
}
public static T ParseXML<T>(this string #this) where T : class
{
var reader = XmlReader.Create(#this.Trim().ToStream(), new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
return new XmlSerializer(typeof(T)).Deserialize(reader) as T;
}
public static T ParseJSON<T>(this string #this) where T : class
{
return JSON.Deserialize<T>(#this.Trim());
}
}
}
All you have to do now, is:
public class JSONRoot
{
public catalog catalog { get; set; }
}
// ...
string xml = File.ReadAllText(#"D:\file.xml");
var catalog1 = xml.ParseXML<catalog>();
string json = File.ReadAllText(#"D:\file.json");
var catalog2 = json.ParseJSON<JSONRoot>();
Here you have some Online XML <--> JSON Converters: Click
Bare minimum working... looks like you are only required to add one attribute.
public class EmailConfiguration
{
public string DataBoxID { get; set; }
public DefaultSendToAddressCollectionClass DefaultSendToAddressCollection { get; set; }
}
public class DefaultSendToAddressCollectionClass
{
[XmlElement]
public string[] EmailAddress { get; set; }
}
Using .NET 3.5:
[XmlRoot]
public class EmailConfiguration
{
[XmlElement]
public string DataBoxID { get; set; }
[XmlElement]
public DefaultSendToAddressCollectionClass DefaultSendToAddressCollection { get; set; }
}
public class DefaultSendToAddressCollectionClass
{
[XmlElement]
public string[] EmailAddress { get; set; }
}
XSD.EXE is the tool that produces classes specifically for the purpose of XML Serialization. If it produces partial classes, that's because they work for XML Serialization. That's not what your problem is.
Try using XSD.EXE and serializing / deserializing. If you get an exception again, then please catch it and then post the results of ex.ToString().
This class will serialize the way you want. I changed your custom collection to a List and used the XmlArrayItem attribute to specify how each email address would be serialized. There are many such attributes to help you fine tune the serialization process.
[Serializable]
public class EmailConfiguration {
private string dataBoxID;
public string DataBoxID {
get { return dataBoxID; }
set { dataBoxID = value; }
}
private List<string> defaultSendToAddressCollection;
[XmlArrayItem("EmailAddress")]
public List<string> DefaultSendToAddressCollection {
get { return defaultSendToAddressCollection; }
set { defaultSendToAddressCollection = value; }
}
public EmailConfiguration() {
DefaultSendToAddressCollection = new List<string>();
}
}
XML serialization requires attributes. The way I've usually done it is to flag the class itself with [Serializable] and [XmlRoot], then mark up public properties with either [XmlElement], [XmlAttribute] or [NoSerialize].
What specific problem are you having?
Related
I am trying to create a new QulaificationType for which the workers have to answer a question to gain the qualification.Below is my C# code. I am getting an error while using createQualificationType method in C# api. Please help.
using System;
using System.Collections.Generic;
using System.Text;
using Amazon.WebServices.MechanicalTurk;
using Amazon.WebServices.MechanicalTurk.Domain;
namespace CreateHITExample
{
class Program
{
static SimpleClient client = new SimpleClient();
static void Main(string[] args)
{
CreateNewHIT();
}
static void CreateNewHIT()
{
**QuestionFormQuestion** question = new QuestionFormQuestion();
question.IsRequired = true;
question.QuestionIdentifier = "1";
**ContentType qnContent = new ContentType();**
QualificationType qualType = client.CreateQualificationType("MyQual2", string.Empty, "My Qualification Type", QualificationTypeStatus.Active, 0, **question**, "680", 600, true, 100);
string qualTypeId = qualType.QualificationTypeId;
Console.WriteLine("Created Qualification Type ID 2: {0}", qualTypeId);
}
}
}
I have to pass the question object as the parameter to CreateQualificationType method.
As you can see from the above piece of code, question object is of class QuestionFormQuestion.
Below are the class definitions that might be of some help.
QuestionFormQuestion Class definition from AWS MTurk dotnet API:
public class QuestionFormQuestion
{
public QuestionFormQuestion();
public AnswerSpecificationType AnswerSpecification { get; set; }
public string DisplayName { get; set; }
public bool IsRequired { get; set; }
[XmlIgnore]
public bool IsRequiredSpecified { get; set; }
**public ContentType QuestionContent { get; set; }**
public string QuestionIdentifier { get; set; }
}
The actual question text goes into the QuestionContent attribute, which is of type "ContentType".
ContentType Class definition from AWS MTurk dotnet API:
public class ContentType
{
public ContentType();
[XmlChoiceIdentifier("ItemsElementName")]
[XmlElement("Application", typeof(ApplicationContentType))]
[XmlElement("Binary", typeof(BinaryContentType))]
[XmlElement("FormattedContent", typeof(String))]
[XmlElement("Text", typeof(String))]
[XmlElement("Title", typeof(String))]
public object[] Items { get; set; }
[XmlElement("ItemsElementName")]
[XmlIgnore]
public ItemsChoiceType[] ItemsElementName { get; set; }
}
I have to move the Actual Question sentence to the [XmlElement("Text", typeof(String))] element of the ContentType object. I dont know the syntax to do that. Please Help.
I was running into the same ValueException error message using the Ruby SDK until I discovered that (unlike ALL the API documentation examples, which showed XML was expected) CreateHit was expecting a Hash, not XML for some parameters (XML for Question, but Hash for QualificationRequirement for example).
In my case it was rejecting a QualificationRequirement when I supplied it XML like they show in the docs, but it worked when I provided it as a Hash.
But since the error message is the same, I suspect that may be what you are running into as well. (The error is language independent... it's not form your SDK, it's what is being returned from AWS when your SDK submits the HIT.)
# does NOT work:
usa_qualification = 'XML STRING LIKE AWS DOCS GIVE'
# DOES work:
usa_qualification = {
:QualificationTypeId => "00000000000000000071",
:Comparator => "EqualTo",
:LocaleValue => { :Country => "US"},
result = mturk.createHIT( :Title => title,
...
:QualificationRequirement => usa_qualification ,
...
I want to create a serializable C# class that would serialize into:
<metadata>
<entry key="">
<dimensionInfo>
<enabled>false</enabled>
</dimensionInfo>
</entry>
<entry key="">false</entry>
</metadata>
Can you help me? I can't handle different entry node structure:/ Too hard for me:P
Let's begin from the lowest class in the hierarchy:
[Serializable]
public class DimensionInfo
{
[XmlElement("enabled")]
public Boolean Enabled { get; set; }
public DimensionInfo()
{
}
}
As you see, there's nothing special here. Then, proceed with the next:
[Serializable]
public class Entry
{
private DimensionInfo _dimensionInfo = default(DimensionInfo);
private Boolean _containsDimensionInfo = true;
[XmlAttribute("key")]
public String Key { get; set; }
[XmlText(typeof(String))]
public String ContainsDimensionInfo
{
get
{
return CheckDimensionContaining().ToString().ToLower();
}
set
{
_containsDimensionInfo = Boolean.Parse(value);
}
}
[XmlIgnore]
public Boolean ContainsDimensionInfoSpecified
{
get { return !CheckDimensionContaining(); }
}
[XmlElement("dimensionInfo")]
public DimensionInfo DimensionInfo
{
get { return _dimensionInfo; }
set { _dimensionInfo = value; }
}
[XmlIgnore]
public Boolean DimensionInfoSpecified
{
get { return CheckDimensionContaining(); }
}
public Entry()
{
Key = String.Empty;
CheckDimensionContaining();
}
private Boolean CheckDimensionContaining()
{
return _containsDimensionInfo = _dimensionInfo != default(DimensionInfo);
}
}
Here the magic begins. With using selective XmlIgnoreAttribute we can decide the ways the object serializes. The main class only wraps a list of Entries:
[Serializable]
[XmlRoot("metadata")]
public class Metadata
{
[XmlElement("entry")]
public List<Entry> Entries { get; set; }
public Metadata()
{
Entries = new List<Entry>();
}
}
How it is made: entry contains dimensionInfo if it exists, and false if it does not. Try out the code sample in console:
Metadata metadata = new Metadata();
metadata.Entries.Add(new Entry()); //Adding empty entry
//Adding entry with info
metadata.Entries.Add(new Entry() { DimensionInfo = new DimensionInfo() });
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Metadata));
using (FileStream fileStream = new FileStream("info.txt", FileMode.Create))
{
xmlSerializer.Serialize(fileStream, metadata);
}
It gave me the following output:
<metadata>
<entry key="">false</entry>
<entry key="">
<dimensionInfo>
<enabled>false</enabled>
</dimensionInfo>
</entry>
</metadata>
However, this code is not perfect and there's a lot of things to improve, but now you have an idea of how it works
If you ever encounter XML files that you need to consume via .Net there is a tool XML Schema Definition Tool (Xsd.exe) that does the conversion automatically.
Its a command-line tool and to open it you use the Start > All
Programs > Visual Studio 2008/10/12/13 > Visual Studio Tools > Visual
Studio Command Prompt
The syntax to create a class from the XML file is described in the MSDN article. I'll give you an overview of the process to get you started.
Save the xml file to the temp dirtectory:
<metadata>
<entry key="">
<dimensionInfo>
<enabled>false</enabled>
</dimensionInfo>
</entry>
<entry key="">false</entry>
</metadata>
Fire up the Visual Studio Command Prompt
To find out all the options enter xsd /?
Now you need to convert the XML file to a XSD file, this is the command:
xsd "C:\temp\File.xml" /c /outputdir:c:\temp
This will create an XSD file in the temp directory.
Then to convert the XSD file to a Serializable C# class this is the command:
xsd "C:\temp\File.xsd" /c /outputdir:c:\temp
This is the resulting C# Serialized class file:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class metadata {
private metadataEntry[] itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("entry", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public metadataEntry[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class metadataEntry {
private metadataEntryDimensionInfo[] dimensionInfoField;
private string keyField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("dimensionInfo", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public metadataEntryDimensionInfo[] dimensionInfo {
get {
return this.dimensionInfoField;
}
set {
this.dimensionInfoField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string key {
get {
return this.keyField;
}
set {
this.keyField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class metadataEntryDimensionInfo {
private string enabledField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string enabled {
get {
return this.enabledField;
}
set {
this.enabledField = value;
}
}
}
Sounds like;
public class Metadata
{
private Dictionary<string, object> entry;
}
Where the dictionary has two item; "false" and another object;
public class dimensionInfo
{
public bool enabled = false;
}
However, you have 2 keys that are empty string. Are you sure the keys shouldn't have a value?
Actually you can create your own custom serialization for any class, so you don't have to stick to the schema when implementing your class.
All you have to do is to create a class which implements the IXmlSerializable interface
You can read more on the topic here:
Custom XML serialization
Otherwise you can use Attributes to control XML serialization.
Using [XmlAttribute] results in serialization as attribute.
Using [XmlText] results in serialization as inner text in the node. (Like the false string inside the other element in your example XML.)
Example:
public class Program
{
static void Main(string[] args)
{
Metadata meta = new Metadata();
meta.entry = new List<Entry>();
var dim = new dimensionInfo();
meta.entry.Add(
new Entry()
{
key = "",
O = dim
}
);
meta.entry.Add(
new Entry()
{
key = "",
text = "false",
O = null
}
);
XmlWriterSettings set = new XmlWriterSettings();
set.NamespaceHandling = NamespaceHandling.OmitDuplicates;
set.OmitXmlDeclaration = true;
set.DoNotEscapeUriAttributes = false;
set.Indent = true;
set.NewLineChars = "\n\r";
set.IndentChars = "\t";
XmlWriter writer = XmlWriter.Create(Console.Out, set);
XmlSerializer ser = new XmlSerializer(typeof(Metadata), "");
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, string.Empty);
ser.Serialize(writer, meta, namespaces);
}
[XmlRoot("metadata")]
public class Metadata
{
[XmlElement]
public List<Entry> entry;
}
public class dimensionInfo
{
[XmlElement]
public bool enabled = false;
}
public class Entry
{
[XmlAttribute] // serialized as attribute
public string key = "";
[XmlText] // serialized as text node
public string text = "";
[XmlElement("dimensionInfo")] // serialized as an element
public dimensionInfo O = null;
}
}
This resulted the following XML:
<metadata>
<entry key=""><dimensionInfo><enabled>false</enabled></dimensionInfo></entry>
<entry key="">false</entry>
</metadata>
You can use XSD.exe to autoGenerate C# class in which you can serialize.
A straight forward answer:
Having your class to implement IXmlSerializable interface and using an XmlSerializer to defining the behavior for all the cases you desire.
private DimensionInfo _value;
public void WriteXml(XmlWriter writer)
{
var valueSerializer = new XmlSerializer(typeof (DimensionInfo));
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
writer.WriteStartElement("entry");
writer.WriteAttributeString("key", string.Empty, string.Empty);
// Here you define how you want your XML structure to look like
// E.g. write an empty XML node in case of a null value
if (_value != null)
{
valueSerializer.Serialize(writer, value, ns);
}
writer.WriteEndElement();
}
Would produce this in XML
<entry key="">
<dimensionInfo>
<enabled>true</enabled>
</dimensionInfo>
</entry>
Or in case of a null value
<entry key="" />
A more detailed example with a XmlSerializableDictionary:
I used an XmlSerializableDictionary approach to produce the XML you provided. Again, you can specify precisely how the produced XML should look like in the WriteXml method.
[XmlRoot("metadata")]
public class XmlSerializableDictionary<TValue> : Dictionary<string, TValue>, IXmlSerializable where TValue : class
{
private const string XmlKeyName = "key";
private const string XmlValueName = "entry";
public void WriteXml(XmlWriter writer)
{
var valueSerializer = new XmlSerializer(typeof (TValue));
var ns = new XmlSerializerNamespaces(); ns.Add("", "");
foreach (var key in Keys)
{
writer.WriteStartElement(XmlValueName);
writer.WriteAttributeString(XmlKeyName, string.Empty, key);
var value = this[key];
// Only serialize the value if value is not null, otherwise write the
// empty XML element.
if (value != null)
{
valueSerializer.Serialize(writer, value, ns);
}
writer.WriteEndElement();
}
}
public void ReadXml(XmlReader reader) { /* left out */ }
public XmlSchema GetSchema() { return null; }
}
The DimensionInfo type for reference
[XmlRoot("dimensionInfo")]
public class DimensionInfo
{
[XmlElement("enabled")]
public Boolean Enabled { get; set; }
}
The following code serializes the dictionary to XML
var xmlSerializableDictionary = new XmlSerializableDictionary<DimensionInfo>
{
{"justakey", new DimensionInfo {Enabled = true}},
{"anotherkey", null}
};
var xmlSerializer = new XmlSerializer(typeof (SerializableDictionary<DimensionInfo>));
xmlSerializer.Serialize(File.Open(#"D:\xmlSerializedDictionary.xml", FileMode.Create), serializableDictionary);
Produced XML file:
<?xml version="1.0"?>
<metadata>
<entry key="justakey">
<dimensionInfo>
<enabled>true</enabled>
</dimensionInfo>
</entry>
<entry key="anotherkey" />
</metadata>
I'm trying to convert my xml file to a list of objects.
private void ReadChangelog()
{
XmlSerializer serializer = new XmlSerializer(typeof(Changelog));
Changelog changelog = (Changelog)serializer.Deserialize(new StringReader("changelog.xml"));
foreach (Release release in changelog.Releases)
{
string version = release.Version;
string date = release.Date;
string changes = release.Changes;
}
}
This is my changelog class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
[XmlRoot()]
public class Changelog
{
private Release[] releases;
public Release[] Releases
{
get { return releases; }
set { releases = value; }
}
}
public class Release
{
private string version;
private string date;
private string changes;
[XmlAttribute]
public string Version
{
get { return version; }
set { version = value; }
}
[XmlAttribute]
public string Date
{
get { return date; }
set { date = value; }
}
[XmlAttribute]
public string Changes
{
get { return changes; }
set { changes = value; }
}
}
And this is my xml
<?xml version="1.0" encoding="utf-8" ?>
<Changelog>
<Releases>
<Release>
<Version>1511</Version>
<Date>25-11-2013</Date>
<Changes>
qzdqzdqzdqzdzdzzqefrsrgsrg
</Changes>
</Release>
<Release>
<Version>1510</Version>
<Date>25-11-2013</Date>
<Changes>
Blabqzdzqdqzdqzd
</Changes>
</Release>
<Release>
</Releases>
</Changelog>
But when I try to run this I get an error
InvalidOperationException, The xml document (1,1) contains an error.
What am I doing wrong?
new StringReader("changelog.xml") doesn't read in the contents of changelog.xml. Instead, this code leaves you trying to deserialize the literal 'changelog.xml' string. I think you want something like new StreamReader("changelog.xml").
StringReader creates stream from string content, not from the file with given path. User StreamReader instead.
Changelog changelog = (Changelog)serializer.Deserialize(new StreamReader("changelog.xml"));
Despite of that, there are couple more errors in your code:
Your document uses elements, and your class declaration uses XmlAttributeAttribute. It won't work together.
Your document is not a correct XML document. It has some elements that are not closed.
I've written a DLL that parses XML and returns Dictionary with tag name and its value. I'm using it in other program called ZennoPoster Project Maker. Here's the code:
XMLWork.XMLWorker worker = new XMLWork.XMLWorker(); // My parse class
string path = #"Z:\New\test.xml";
Dictionary<string, string> data = worker.GetData(path); // GetData - method, that returns
// data from XML
project.Variables["second_name"].Value = data["second_name"];
This block of code I must remake into XMLWorker class method and return a project type and in ZennoPoster I have to with 1 line of code return data. How can I do it?
Assuming that you have the following simplified types:
namespace Objects
{
public class Project
{
public Dictionary<string, Variable> Variables { get; set; }
}
public class Variable
{
public object Value { get; set; }
}
}
You could structure your XMLWorker class like this:
using Objects;
public class XMLWorker
{
public Project Project { get; private set; }
public XMLWorker(string path)
{
Project = new Project();
Dictionary<string, string> data = GetData(path);
Project.Variables["second_name"].Value = data["second_name"];
}
internal Dictionary<string, string> GetData(string path)
{
// method implementation
}
}
Sample usage:
var project = (new XMLWork.XMLWorker(#"Z:\New\test.xml")).Project;
I have a models that are used for serializing data to xml.
Ex
public class File : IFile
{
[XmlAttribute]
public string ObjectId;
public string OriginalFileName { get; set; }
public string FileName { get; set; }
public int Size { get; set; }
public string Note { get; set; }
public static explicit operator File(FileItem a) // explicit File to FileItem conversion operator
{
File b = new File(); // explicit conversion
b.ObjectId = a.ObjectId;
b.Note = a.Note;
b.FileName = a.FileName;
b.OriginalFileName = a.OriginalFileName;
b.Size = a.Size;
return b;
}
}
These classes are mainly used for reading and saving xml documents inside a worddocument.
Inside the main application i need data to be observable so in this case i use prism and the classes inherits from Notificationobject.
Ex
public class FileItem : NotificationObject, IFile
{
public FileItem()
{
}
public static explicit operator FileItem(File a) // explicit File to FileItem conversion operator
{
FileItem d = new FileItem(); // explicit conversion
d.ObjectId = a.ObjectId;
d.Note = a.Note;
d.FileName = a.FileName;
d.OriginalFileName = a.OriginalFileName;
d.Size = a.Size;
return d;
}
private string _objectid;
public string ObjectId
{
get { return _objectid; }
set
{
if (!value.Equals(_objectid))
{
_objectid = value;
this.RaisePropertyChanged(() => this.ObjectId);
}
.................
So what i do is that i first read xml files into the File class and then i need to convert it into FileItem class and when i want to save it back to xml i need to do the reverse conversion again. This seems a little bit unessesary to me. I could think of a solution where i serialize directly into FileItem but i need to keep File simple as it is defined in a assembly that is used by other components that does not need notificationobject and where prism assemblies will not be installed.
Any ideas on how to simplify this.
You could use AutoMapper to automatically map from one object to the other.