简体   繁体   中英

XML deserialize getting null

I have an xml, I need to serialize.

<Configuration>   
    <Configs>
        <tester>
            <test>gabc</test>
            <test>def</test>
        </tester>
    </Configs>
</Configuration>

This is the class used.

public class Configuration
{
   public tester Configs{ get; set; }
}

public class tester 
{
   // The web site name
   public string[] test{ get; set; }
}

Configuration obj = new Configuration();
XmlSerializer mySerializer = new XmlSerializer(typeof(Configuration));
FileStream myFileStream = new FileStream(SettingsFile, FileMode.Open);
obj = (Configuration)mySerializer.Deserialize(myFileStream);
myFileStream.Close();

I am getting obj.configs.test as null.

How to get the values used in the test node?

You need to specify the XmlArray and XmlArrayItem

public class tester
{
   //The web site name
   [XmlArray("tester")]
   [XmlArrayItem("test")]
   public string[] test { get; set; }
}

The xml config file should use <string> tag

So something like this:

<tester>
<string>gabc</string>
<string>def</string>
</tester>

Your current classes serialize as below:

<?xml version="1.0" encoding="utf-16"?>
<Configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Configs>
    <test>
      <string>gabc</string>
      <string>def</string>
    </test>
  </Configs>
</Configuration>

I created this using the code:

 Configuration obj = new Configuration
                        {
                            Configs = new tester
                                          {
                                              test = new string[]
                                                         {
                                                             "gabc", "def"
                                                         }
                                          }
                        };

XmlSerializer serializer = new XmlSerializer(typeof(Configuration));

string output;

using (StringWriter writer = new StringWriter())
{
    serializer.Serialize(writer, obj);
    output = writer.ToString();
}

Use that code to modify the class so that it serializes the way you want to deserialize it. Serialization works two-way.

You can either implement the IXmlSerializable interface or use the xml range of attributes.

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