Search code examples
c#xml-serializationxml-namespacesxmlserializer

xmlns attribute not produced for nested elements


I have a class with a nested list of another class, like this:

public class Departement {
     [XmlElement (Namespace = "http://tempuri.org/")]
     string Id;
     [XmlElement (Namespace = "http://tempuri.org/")]
     List<Student> listStident = new List<Student> ();
 }
 public class Student 
 {
     [XmlElement (Namespace = "http://tempuri.org/")]
     string firstName;
     [XmlElement (Namespace = "http://tempuri.org/")]
     string lastName;
 }

When I try to serialize an array of Departements, I get an xml like that:

<ArrayOfDepartement xmlns="http://www.w3...">
    <Departement>
        <id xmlns== "http://tempuri.org/">1234567890</id>
        <Student xmlns== "http://tempuri.org/">
            <firstName>med</firstName>
            <lastName>ali</lastName>
        </Student>
        <Student xmlns== "http://tempuri.org/">
            <firstName>joe</firstName>
            <lastName>doe</lastName>
        </Student>
    </Departement>
</ArrayOfDepartement>

No namespace attribute is generated for the nested elements. The code I use to serialize is:

public void Serialize(object oToSerialize)
{
    XmlSerializer xmlSerializer =  new XmlSerializer(oToSerialize.GetType());
    XmlDocument xDoc = new XmlDocument();
    using (var stream = new MemoryStream())
    {
        xmlSerializer.Serialize(stream, oToSerialize);
        stream.Flush();
        stream.Seek(0, SeekOrigin.Begin);
        xDoc.Load(stream);
    }
}

Solution

  • The XML Namespaces specification in section 6.1 states:

    The scope of a namespace declaration declaring a prefix extends from the beginning of the start-tag in which it appears to the end of the corresponding end-tag, excluding the scope of any inner declarations with the same NSAttName part. In the case of an empty tag, the scope is the tag itself.

    Such a namespace declaration applies to all element and attribute names within its scope whose prefix matches that specified in the declaration.

    Therefore, the data structure is serialized without repeated xmlns="http://tempuri.org/" attributes on the nested firstName and lastName elements as they would be superfluous. The reason why id and each Student elements have their own xmlns atribute is that they are siblings, forming disjoint namespace declaration scopes.

    In other words, the XML produced by your code is correct and as expected. If there were extra xmlns attributes on the nested elements, it would have no semantical effect. I would be more concerned about the fact that that you are not serializing a specific root class but a plain Departement[] (unless it's just for debugging / experimenting purposes).