在反序列化xml Http响应时遇到问题

时间:2016-02-26 10:05:23

标签: c# xml xml-serialization deserialization

我正在尝试将xml格式的HTTPresponse反序列化为Object。

XML响应:

<?xml version="1.0" encoding="utf-8" ?> 
- <NPIList>
- <NPI>
  <NPI>1003000118</NPI> 
  <EntityType>Organization</EntityType> 
  <IsOrgSubpart>N</IsOrgSubpart> 
  <OrgName>STEVEN ENGEL PEDIATRICS</OrgName> 
  <FirstLineMailingAddress>1700 NEUSE BLVD</FirstLineMailingAddress> 
  <MailingAddressCityName>NEW BERN</MailingAddressCityName> 
  <MailingAddressStateName>NC</MailingAddressStateName> 
  <MailingAddressPostalCode>28560-2304</MailingAddressPostalCode> 
  <MailingAddressCountryCode>US</MailingAddressCountryCode> 
  <MailingAddressTelephoneNumber>252-637-3799</MailingAddressTelephoneNumber> 
  <MailingAddressFaxNumber>252-633-0944</MailingAddressFaxNumber> 
  <FirstLinePracticeLocationAddress>1700 NEUSE BLVD</FirstLinePracticeLocationAddress> 
  <PracticeLocationAddressCityName>NEW BERN</PracticeLocationAddressCityName> 
  </NPI>
  </NPIList>

我的代码检索xmlhttp响应并反序列化如下:

using (var response = (HttpWebResponse)request.GetResponse())
      {
        var responseValue = string.Empty;

        if (response.StatusCode != HttpStatusCode.OK)
        {
          var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
          throw new ApplicationException(message);
        }
       Stream respStream = response.GetResponseStream();
        XmlSerializer ser = new XmlSerializer(typeof(NPIList));
        var resp = (NPIList)ser.Deserialize(respStream);

                    response.Close();
}

我创建了我的对象类

   public class NPIList
    {
        public List<NPIObj> NPI { get; set; }
    }

我将变量“resp”的计数设为零。

这是我的NPIObj课程:

 public class NPIObj
    {
        public string EntityType { get; set; }
        public string FirstLineMailingAddress { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string MailingAddressCityName { get; set; }
        public string MailingAddressCountryCode { get; set; }
        public string MailingAddressPostalCode { get; set; }
        public string MailingAddressStateName { get; set; }
        public string MiddleName { get; set; }
        public string NamePrefix { get; set; }
        public string NPI { get; set; }
        public string OrgName { get; set; }
        public string SecondLineMailingAddress { get; set; }
     }

任何人都可以帮助我解决可能存在的问题。

1 个答案:

答案 0 :(得分:0)

尝试添加XmlElement属性,例如:

public class NPIList
    {
        [XmlElement("NPI")]
        public List<NPIObj> NPI { get; set; }
    }