Deserialize XML without namespaces but in a class expecting namespaces

前端 未结 4 1432
感动是毒
感动是毒 2021-01-02 10:55

Duplicate:
Omitting all xml namespaces when serializing an object? Not the same.. I want in the other way: Deserialize!


I

4条回答
  •  伪装坚强ぢ
    2021-01-02 11:05

    In order to deserialize XML without namespace add XmlRoot attribute to the class that represents the top of your hierarchy:

    [XmlRoot(ElementName="plugins", Namespace="")]
    

    In my example the Xml has no namespace and starts like

    <...
    

    The class that it deserializes to:

    [XmlRoot(ElementName="plugins", Namespace="")]
    public class Plugins
    {
       //...
    }
    

    Obviously, your situation may be a slightly different, but this code works for me:

    using (FileStream stream = File.Open(filePath, FileMode.Open))
    {
       XmlReader reader = new XmlTextReader(stream);                
       XmlSerializer serializer = new XmlSerializer(typeof(Plugins));
       var plugins = (Plugins)serializer.Deserialize(reader);
    }
    

    -Stan

提交回复
热议问题