Search code examples
c#xmlasp.net-web-api2xml-serializationxml-deserialization

Deserialization of XML having multiple namespace in root tag


If i just have a single namespace i am able to deserialize by including the namespace as this in class [XmlRoot(ElementName = "metadata", Namespace = "http://medical.nema.org/mint")]

How to deserialize if i have multiple namespaces in XML ? How should my class look like ?

Part of XML file

<metadata type="DICOM" version="1.0" xmlns="http://medical.nema.org/mint"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://medical.nema.org/mint http://medical-imaging-network-transport.googlecode.com/files/mint-datadictionary.xsd">

Class

[Serializable]
    [XmlRoot(ElementName = "metadata")]

    public class Dicom
    {
        [XmlAttribute]
        public string type { get; set; }

        [XmlAttribute]
        public string version { get; set; }

        [XmlElement("attributes")]
        public List<attributes> attributes { get; set; }

        [XmlElement("study-attributes")]
        public List<studyattributes> studyattributes {get; set;}

        [XmlElement("series-attributes")]
        public List<seriesattributes> seriesattributes{get;set;}
}

Controller class where i am deserializing

XmlSerializer deserializer = new XmlSerializer(typeof(Dicom));
        TextReader reader = new StreamReader(@"F:\DICOM.xml");
  object obj = deserializer.Deserialize(reader);

Solution

  • You need to add the namespace property to your class definition.

    [XmlRoot(ElementName = "metadata", Namespace = "http://medical.nema.org/mint")]
    

    Also, if you have access to the full xsd or even xml file you can use the xsd.exe tool which ships as part of Visual Studio to generate the required classes.