Deserializing an XML array from a web api

别等时光非礼了梦想. 提交于 2019-12-02 06:35:31

Basically, you need to support the default XML namespace in your XML file - you can either do this by specifying it on the StudentCollection:

[System.Xml.Serialization.XmlRoot("ArrayOf__ptd_student_charges")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.datacontract.org/2004/07/something.something", IsNullable = false)]
public class StudentCollection
{
    [XmlArray("ArrayOf__ptd_student_charges")]
    [XmlArrayItem("__ptd_student_charges", typeof(Student))]
    public Student[] StudentArray { get; set; }
}

and the actual Student class:

[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.datacontract.org/2004/07/something.something", IsNullable = false)]
public class Student
{
   ..........
}

or you can specify it programmatically when you deserialize:

XmlSerializer serializer = new XmlSerializer(typeof(StudentCollection),
                                             "http://schemas.datacontract.org/2004/07/something.something");

That second parameter for the XmlSerializer is the default XML namespace to use when deserializing the XML content.

Extra tipp: if you ever have an XML file again, and you need to get the C# code classes that represent that XML - if you have Visual Studio 2012 or newer, just create a new code class, copy your XML file into the clipboard, and then use Edit > Paste Special > Paste XML as classes and you get all your C# including all XML attribute and XML namespaces and everything pasted into your Visual Studio right there

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!