0

I have two applications: X and Y. X has a set of variables (stored in an object of a class), which have to be transferred to Y. I am planning to use an XML-file as a record stored on disk that can be accessed by name by both applications. X writes the data to that XML-file and Y reads it.

I thought I can use XmlSerializer (System.Xml.Serialization) to accomplish this. With XmlSerializer I can create an XML file that looks like this:

<MonsterCollection>
  <Monsters>
    <Monster name="a">
     <Health>5</Health>
    </Monster>
    <Monster name="b">
     <Health>3</Health>
    </Monster>
  </Monsters>
</MonsterCollection>

When Y reads this XML file, it does not know the actual data type of variables Health. Therefore, the original class has to be defined in both X and Y. Is there a way to store the datatypes in the XML-file, as well? In the end, I would like to accomplish something like this:

<Monster name="a" type="" help="This is a monster">
  <var name="Health" type="uint16" val="5" help="Healthiness of this monster" /> 
</Monster>
<Monster name="b" type="" help="This is a monster">
  <var name="Health" type="uint16" val="3" help="Healthiness of this monster" /> 
</Monster>
Boozzz
  • 245
  • 1
  • 6
  • 19

1 Answers1

0

you can use the below mentioned code

 public class Monster 
{
    [XmlAttribute("name")]
    public string name {get;set;}
    [XmlAttribute("type")]
    public string type {get;set;}
    [XmlAttribute("val")]
    public int val { get; set; }
}

for ref serialize-object-to-element

Community
  • 1
  • 1
Dhaval Patel
  • 7,471
  • 6
  • 37
  • 70
  • Thank you for your answer!! I'm wondering, if there is a way to avoid declaring class "Monster" in both applications X and Y. Even when I use XmlAttribute to store the data as attributes (instead of elements), I still have to declare class "Monster" in application Y, as well. Is that correct? – Boozzz May 19 '14 at 08:26
  • if you are using dll of first application into your second application then you don't need to create that class again – Dhaval Patel May 19 '14 at 08:36
  • Thanks so much! This is exactly what I was looking for. I just have to use dll's :-). That way, I do not even have to use XmlAttribute anymore. Or do you know how I could use the datatype stored as XmlAttribute, when I deserialize the XML-file in application Y? – Boozzz May 19 '14 at 08:48
  • you can use the typeof key – Dhaval Patel May 19 '14 at 08:53
  • you can take the value in var and that cast it with value you received from xml. – Dhaval Patel May 19 '14 at 08:59