将简单的xml反序列化为List

本文关键字:List string 反序列化 简单 xml | 更新日期: 2023-09-27 17:50:55

我知道这是一个相当愚蠢的问题,但是我被卡住了…(类似的问题,这里没有有用的答案)

my XML is

<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; }
}

但是当我试图反序列化时,我得到一个nullerroreexception

为什么不工作?

编辑:

反序列化代码:

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;}
}

(实际上更复杂)

将简单的xml反序列化为List<string>

如果没有看到实际执行序列化的代码,很难找到错误。但是,您可以尝试告诉序列化器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)};
    }
}

您需要像这样使用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);
}

这是一个解决方案

        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