XML反序列化为null
本文关键字:null 反序列化 XML | 更新日期: 2023-09-27 18:20:41
我有一个xml,我需要序列化。
<Configuration>
<Configs>
<tester>
<test>gabc</test>
<test>def</test>
</tester>
</Configs>
</Configuration>
这是所使用的类。
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();
我得到的obj.configs.test为null。
如何获取测试节点中使用的值?
您需要指定XmlArray和XmlArrayItem
public class tester
{
//The web site name
[XmlArray("tester")]
[XmlArrayItem("test")]
public string[] test { get; set; }
}
xml配置文件应使用<string>
标记
这样的东西:
<tester>
<string>gabc</string>
<string>def</string>
</tester>
您当前的类序列化如下:
<?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>
我使用代码创建了这个:
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();
}
使用该代码修改类,使其按照反序列化的方式进行序列化。序列化是双向的。
您可以实现IXmlSerializable
接口,也可以使用xml范围的属性。