2

I want to deserialize a XML node to a class, with all the subnodes values into class properties

I got this error

  •   ex  {"There is an error in XML document (1, 2)."}   System.Exception {System.InvalidOperationException}
    

and the message of the exception

  •   InnerException  {"<LITERALS xmlns=''> was not expected."} // If i use InnerXml it would be REVISION xmlns...
    

I tried Outer and Inner XML with a lot of solutions that appear in stackoverflow. I dont know why it adds xmlns

My xml is like that:

<root>
  <LITERALS>
    <REVISION>Rev.</REVISION>
    <SERIE>Serie</SERIE>
  </LITERALS>
  <MORENODES></MORENODES>
  <MORENODES></MORENODES>
</root>

And my class Literals to deserialize the xml node

{
    // I tried these options that i saw in a post
    // [XmlRoot(ElementName="LITERALS")]
    // [Serializable, XmlRoot("LITERALS")]
    [XmlRoot(Namespace = "www.idk.com", ElementName = "LITERALS", DataType = "string", IsNullable = true)]
    public class Literals
    {
        [XmlElement(ElementName = "REVISION")]
        public string REVISION { get; set; }

        [XmlElement(ElementName = "SERIE")]
        public string SERIE { get; set; }
    }
}

My code

                XmlNode literalsNodo = courseNodo.SelectSingleNode("LITERALS");
                XmlRootAttribute xRoot = new XmlRootAttribute("LITERALS");
                xRoot.ElementName = "LITERALS";
                xRoot.Namespace = "http://www.idk.com";
                xRoot.IsNullable = true; 
                  
                 
                if (literalsNodo != null)
                {

                    XmlSerializer xs = new XmlSerializer(typeof(Literals),xRoot);
                    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(literalsNodo.InnerXml));

                    literals = (Literals)xs.Deserialize(ms);
                }
                
seergius96
  • 86
  • 7
  • You're missing a Root class, aka a class that can deserialize your root element that contains a property with your Literals class. – rene Sep 30 '22 at 10:52
  • What are you adding namespace to the xml classes when you do not have any namespaces in the xml? Remove namespace attributes in the classes. – jdweng Sep 30 '22 at 11:01
  • 1
    It's missing the namespace. Should be `` so your XML does not match your class attribute – Charlieface Sep 30 '22 at 11:27
  • 1
    The following may be helpful: https://stackoverflow.com/a/73640395/10024425, https://stackoverflow.com/a/72589790/10024425, and https://stackoverflow.com/q/68215415/10024425. – Tu deschizi eu inchid Sep 30 '22 at 17:32

0 Answers0