XML deserialize getting null

I have 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 get obj.configs.test as null.

How to get the values ​​used in the node test?

+4
source share
3 answers

You need to specify XmlArray and XmlArrayItem

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

The xml configuration file should use the <string>

So something like this:

 <tester> <string>gabc</string> <string>def</string> </tester> 
0
source

Your current classes are serialized as shown 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 with 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 this code to change the class so that it is serialized the way you want to deserialize it. Serialization works in two ways.

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

0
source

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


All Articles