1

I know it's a pretty stupid question, but I'm stuck... (similar question with no useful answer here)

my xml is

<Param>
    <MyList>
        <mynode>aaa</mynode>
        <mynode>bbb</mynode>
        <mynode>ccc</mynode>
        <mynode>ddd</mynode>
    </MyList>
</Param>

and I have a class like this

public class MyClass
{
    [XmlArray("MyList")]
    [XmlArrayItem("mynode")]
    public List<string> MyList { get; set; }
}

but when i try to deserialize i get a nullerrorexception

why this doesn't work?

edit: deserialize code:

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

and

public class Param
{
    public MyClass MyClass {get; set;}
}

(actually more complex)

Community
  • 1
  • 1
Doc
  • 5,078
  • 6
  • 52
  • 88

3 Answers3

3

Without seeing the code that actually does the serialization it is hard to find the bug. However, you can try telling the serializer what is the top element of the xml:

[XmlRoot("Param")]
public class MyClass
{
    [XmlArray("MyList")]
    [XmlArrayItem("mynode")]
    public List<string> MyList { get; set; }
}

EDIT: The serializer should be of type 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)};
    }
}
Grzenio
  • 35,875
  • 47
  • 158
  • 240
1

You need to use XmlRoot attribute with MyClass like this:

[XmlRoot("Param")]
public class MyClass
{
    [XmlArray("MyList")]
    [XmlArrayItem("mynode")]
    public List<string> MyList { get; set; }
}

Then you can use this code to Deserialize your xml:

XmlSerializer se = new XmlSerializer(typeof(MyClass));
using(var stream = File.OpenRead("filePath"))
{
   var myClass = (MyClass) se.Deserialize(stream);
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

This would be one solution

        XmlSerializer rializer = new XmlSerializer(typeof(MyClass));

        using (var stream = File.OpenRead("C:\\Users\\t0408\\Desktop\\testfor.xml"))
        {
            MyClass myClass = (MyClass)rializer.Deserialize(stream);
        }

// Class should be like this

        [XmlRoot("Param")]
         public class MyClass
         {
           [XmlArrayItem("mynode")]
           public List<string> MyList { get; set; }
         }

Thanks Lineesh

Lineesh
  • 106
  • 1
  • 1
  • 6