简体   繁体   中英

When serializing/deserializing XML data, do the XML elements and the class attributes have the same name?

For example:

Here's a simple class.

class Hero
{
    public string faction;
    public string name;
    public HeroType herotype;
}

And here's the XML counterpart.

<Hero>
    <android>
        <Faction>evil</Faction>
        <nombre>android</nombre>
    </android>
</Hero>

Do the attributes have to be exactly the same in order to serialize information?

My main purpose is to "load" information to the Hero class with information from my XML file.

You can decorate your fields with [XmlElement(...)] to specify an alternate name. Also they do not have to be in the same order. However the Xml you specified doesn't fit the structure of the classes you specified.

Modify your Xml to something like this:

<Hero>
    <Name>android</Name>
    <Faction>evil</Faction>
    <HeroType>Agility</HeroType>
</Hero>

Unless you specify otherwise (as Aviad P. says, by decorating a property with the [XmlElement()] attribute), the name in the XML will be matched exactly to the property name, and vice versa.

The ordering should be insignificant. I say "should be" because whether not it actually is insignificant depends on how you've designed your class.

While in general it's good practice to have property setters be side-effect-free, when you're dealing with XML deserialization, it's essential. During deserialization, properties will be set to their values in the order that they appear in the XML.

So if you have this class:

public class Test
{
   private string _Foo;
   public string Foo { set { _Foo = value; _Baz="Foo"; } get { return _Foo; }}

   private string _Bar;
   public string Bar { set { _Bar = value; _Baz="Bar"; } get { return _Bar; }}

   private string _Baz;
   public string Baz { set { _Baz = value; } get { return _Baz; }}
}

then XML in which Foo appears before Bar will set Baz to "Foo", while XML in which Bar appears before Foo will set Baz to "Bar".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM