How to deserialize this simple xml configuration using the XmlSerializer class?

I have the following xml that I would 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 convert it to 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 to deserialize it using the following code, a configuration object is created, but the lines are null.

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

I tried to use xsd.exe to create xsd and then create a class based on this, but there is too much clutter generated by this tool. I think I'm near. What am I missing?

0
source share
4 answers

You cannot serialize / deserialize internal properties - they must be publicly available.

+7
source

. . , , / .xml . , . , , .

+5

... XmlSerializer. , , , . , , code stink

Linq XML .... , linq .

, WCF datacontract... .

, xml docs . , Linq, , . , . , XmlSerializer " ", Linq to XML - " ".

, .

+1

You can use XSD.exe to generate a class from XSD (XML Schema Definition). This creates a useful class structure that can serialize and deserialize the corresponding XML.

+1
source

Source: https://habr.com/ru/post/1698475/


All Articles