views:

1334

answers:

4

I have the following xml I'd like to deserialize into a class

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <element1>String1</element1>
  <element2>String2</element2>
</root>

I am trying to serialize it into the following class:

    [XmlRoot("root")]
    public class root
    {
        [XmlElement("element1")]
        internal string element1 { get; set; }

        [XmlElement("element2")]
        internal string element2 { get; set; }
    }

When I try deserializing it using the following code, the config object is instantiated, but the strings are null.

     using (TextReader reader = new StreamReader(configFile))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(root));
            this.config = (root)serializer.Deserialize(reader);
        }

I've tried using xsd.exe to create an xsd, and then create a class based off of that, but there is too much clutter generated by that tool. I think I'm close here. What am I missing?

+7  A: 

You can't serialise/deserialise internal properties - They have to be public.

Brody
+4  A: 

I concur with Brody as to the nature of your problem. However, you may have an objection to making these fields public. The way I have handled this problem in the past is to create a serializable class whose only purpose is to read/write .xml and has all of its fields public. Then create a new class which is the external interface. It takes the serializable class as an argument of a constructor and the external class provides public properties which controls the access to the serializable class.

Kevin
+1  A: 

To follow up on my implementation... I ended up abandoning using the XmlSerializer class all together. The classes I was deserializing were pretty complex and contained lists of other objects that needed to be serialized. The amount of attributes I had to add to my classes made the code stink

I ended up using Linq to XML to do the deserialization.... the complexity of the class delcarations went down, but the linq statement eneded up being rather complex.

If I were to do it again, I might have thought about using WCF and the datacontract serializer... That might have also been difficult to do also.

I'm curious how people are deserializing xml docs into objects these days. After getting my head around Linq statements, I think this might be the way to go. The objects are much simpler to create, and they don't need to be public. It also seems like the XmlSerializer is "old-school" while Linq to XML is more "new-school".

I'd love to hear what others had to say.

Peter Walke
Try using XSD.exe
Brody
+1  A: 

You can use XSD.exe to generate a class from an XSD (XML Schema Definition). This produces a usable class structure that can serialise and deserialise the relevant XML.

Brody