如何将XML从外部API加载到本地对象

时间:2018-04-09 15:12:16

标签: c# xml

我尝试使用以下网址将外部网络服务中的XML加载到对象中:http://data.parliament.uk/membersdataplatform/services/mnis/members/query/fymp=ST1

从我在网上找到的内容来看,我已经制作了这些对象并添加了XMLRoot和XMLElement属性:

public class Member
    {
        [XmlElement("DisplayAs")]
        string DisplayAs { get; set; }
        [XmlElement("ListAs")]
        string ListAs { get; set; }
        [XmlElement("FullTitle")]
        string FullTitle { get; set; }
        [XmlElement("LayingMinisterName")]
        string LayingMinisterName { get; set; }
        [XmlElement("DateOfBirth")]
        string DateOfBirth { get; set; }
        [XmlElement("DateOfDeath")]
        string DateOfDeath { get; set; }
        [XmlElement("Gender")]
        string Gender { get; set; }
        [XmlElement("Party")]
        string Party { get; set; }
        [XmlElement("House")]
        string House { get; set; }
        [XmlElement("MemberFrom")]
        string MemberFrom { get; set; }
        [XmlElement("HouseStartDate")]
        string HouseStartDate { get; set; }
        [XmlElement("HouseEndDate")]
        string HouseEndDate { get; set; }
        [XmlElement("CurrentStatus")]
        CurrentStatus CurrentStatus { get; set; }
    }

    public class CurrentStatus
    {
        [XmlElement("Name")]
        string Name { get; set; }
        [XmlElement("Reason")]
        string Reason { get; set; }
        [XmlElement("StartDate")]
        string StartDate { get; set; }
    }

    [XmlRoot("Members")]
    public class Members
    {
        [XmlElement("Member")]
        List<Member> MemberList { get; set; }
    }

我可以使用XML Text Reader从URL读取XML:

public void GetMemberByPostcode(string postcode)
        {
            string Url = "http://data.parliament.uk/membersdataplatform/services/mnis/members/query/fymp=" + postcode;
            XmlTextReader reader = new XmlTextReader(Url);

        }  

但我似乎无法在网上找到任何可以让我从这里获得XML数据填充对象的内容。任何人都可以建议最好的方法来做到这一点,或指向我直接的教程或帖子,告诉我它是如何完成的?

2 个答案:

答案 0 :(得分:1)

第一个问题是你的模型应该有公共属性,使用setter和getter XML反序列化器才能工作。 在更改之后使用此代码:

string Url = "http://data.parliament.uk/membersdataplatform/services/mnis/members/query/fymp=ST1";
XmlTextReader reader = new XmlTextReader(Url);

var serializer = new XmlSerializer(typeof(Members));
var members = (Members)serializer.Deserialize(reader);

答案 1 :(得分:0)

使用WebClient.DownloadString Method将XML作为字符串获取。

WebClient client = new WebClient();
string xml= client.DownloadString(address);

然后将XML字符串反序列化为类的实例。

var serializer = new XmlSerializer(typeof(Members));
using (var reader = new StringReader(xml))
{
  var members= (Members)serializer.Deserialize(reader);
}