Deserializing an XML array from a web api

前端 未结 1 1695
无人及你
无人及你 2021-01-25 17:31

First off, I followed the answer given here, but I still can not get the following to work.

I am retrieving XML from a web API, and the results returned are as such:

相关标签:
1条回答
  • 2021-01-25 17:39

    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

    0 讨论(0)
提交回复
热议问题