我知道这是一个非常愚蠢的问题,但我被卡住了......(类似的问题没有有用的答案here)
我的xml是
<Param>
<MyList>
<mynode>aaa</mynode>
<mynode>bbb</mynode>
<mynode>ccc</mynode>
<mynode>ddd</mynode>
</MyList>
</Param>
我有一个这样的课程
public class MyClass
{
[XmlArray("MyList")]
[XmlArrayItem("mynode")]
public List<string> MyList { get; set; }
}
但是当我尝试反序列化时,我得到了一个nullerrorexception
为什么这不起作用?
修改 反序列化代码:
public static Param InitConfig(string Path)
{
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Param";
xRoot.IsNullable = true;
XmlSerializer serializer = new XmlSerializer(typeof(Param), xRoot);
using (StreamReader reader = new StreamReader(Path))
{
return (Param)serializer.Deserialize(reader);
}
}
和
public class Param
{
public MyClass MyClass {get; set;}
}
(实际上更复杂)
答案 0 :(得分:3)
如果没有看到实际进行序列化的代码,就很难找到错误。但是,您可以尝试告诉序列化程序xml的最高元素是什么:
[XmlRoot("Param")]
public class MyClass
{
[XmlArray("MyList")]
[XmlArrayItem("mynode")]
public List<string> MyList { get; set; }
}
编辑:
序列化程序应为MyClass
类型:
public static Param InitConfig(string Path)
{
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Param";
xRoot.IsNullable = true;
XmlSerializer serializer = new XmlSerializer(typeof(MyClass), xRoot);
using (StreamReader reader = new StreamReader(Path))
{
return new Param {MyClass = (MyClass)serializer.Deserialize(reader)};
}
}
答案 1 :(得分:1)
您需要将XmlRoot
属性与MyClass
一起使用,如下所示:
[XmlRoot("Param")]
public class MyClass
{
[XmlArray("MyList")]
[XmlArrayItem("mynode")]
public List<string> MyList { get; set; }
}
然后您可以将此代码用于Deserialize
您的xml:
XmlSerializer se = new XmlSerializer(typeof(MyClass));
using(var stream = File.OpenRead("filePath"))
{
var myClass = (MyClass) se.Deserialize(stream);
}
答案 2 :(得分:0)
这将是一个解决方案
XmlSerializer rializer = new XmlSerializer(typeof(MyClass));
using (var stream = File.OpenRead("C:\\Users\\t0408\\Desktop\\testfor.xml"))
{
MyClass myClass = (MyClass)rializer.Deserialize(stream);
}
//类应该是这样的
[XmlRoot("Param")]
public class MyClass
{
[XmlArrayItem("mynode")]
public List<string> MyList { get; set; }
}
由于 Lineesh