>我有一个类,其中包含另一个类的嵌套列表,如下所示:
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;
}
当我尝试序列化Departement
的数组时,我得到这样的 xml:
<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>
不会为嵌套元素生成命名空间属性。我用来序列化的代码是:
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);
}
}
第 6.1 节中的 XML 命名空间规范指出:
声明前缀的命名空间声明的范围从它出现的开始标记的开头延伸到相应结束标记的末尾,不包括具有相同 NSAttName 部分的任何内部声明的范围。对于空标记,范围是标记本身。
此类命名空间声明适用于其作用域内前缀与声明中指定的前缀匹配的所有元素和属性名称。
因此,序列化数据结构时,嵌套firstName
和lastName
元素上没有重复的xmlns="http://tempuri.org/"
属性,因为它们是多余的。id
和每个Student
元素之所以有自己的xmlns
,是因为它们是同级,形成了不相交的命名空间声明作用域。
换句话说,代码生成的 XML 是正确的,并且符合预期。如果嵌套元素上有额外的xmlns
属性,则不会产生语义效果。我更关心的不是您序列化特定的根类,而是普通Departement[]
(除非只是出于调试/实验目的)。