简体   繁体   English

无法将XML字符串反序列化为包含List的对象

[英]Cannot deserialize XML string to object containing List

Here is my serialization methods: 这是我的序列化方法:

public static T DeserializeFromXml<T>(string xml)
{
    try
    {
         var root = new XmlRootAttribute()
         {
             ElementName = "PatientDS",
             Namespace = ""
         };

         T result;
         var serializer = new XmlSerializer(typeof(T), root);
         using (TextReader reader = new StringReader(xml))
         {
            result = (T)serializer.Deserialize(reader);
         }
         return result;
    }
    catch (Exception ex)
    {
        return default(T);
    }
}

public static string Serialize<T>(T obj)
{
    try
    {
       var serializer = new XmlSerializer(typeof(T));
       using (var writer = new StringWriter())
       {
           serializer.Serialize(writer, obj);
           return writer.ToString();
       }
    }
    catch (Exception ex)
    {
        return String.Empty;
    }
}

Here is the object I am trying to deserialize to: 这是我要反序列化的对象:

public class PatientDS
{
    [XmlElement("Patient")]
    public Patient Patient { get; set; }
}

    [Serializable]
    public class Patient
    {
        [XmlElement("PatientID")]
        public Guid PatientID { get; set; }

        [XmlElement("Gender")]
        public string Gender { get; set; }

        [XmlElement("PatientCategory")]
        public string PatientCategory { get; set; }

        [XmlElement("SiteOfDisease")]
        public string SiteOfDisease { get; set; }

        [XmlElement("Outcome")]
        public string Outcome { get; set; }

        [XmlElement("RegistrationYear")]
        public int RegistrationYear { get; set; }

        [XmlElement("RegistrationNo")]
        public int RegistrationNo { get; set; }

        [XmlElement("RegistrationDate")]
        public DateTime RegistrationDate { get; set; }

        [XmlElement("Name")]
        public string Name { get; set; }

        [XmlElement("Surname")]
        public string Surname { get; set; }

        [XmlElement("IDNumber")]
        public string IDNumber { get; set; }

        [XmlElement("BirthDate")]
        public DateTime BirthDate { get; set; }

        [XmlElement("TypeOfResistantTB")]
        public string TypeOfResistantTB { get; set; }

        [XmlElement("TreatmentStartDate")]
        public DateTime TreatmentStartDate { get; set; }

        [XmlElement("OutcomeDate")]
        public DateTime OutcomeDate { get; set; }

        [XmlElement("IsActive")]
        public bool IsActive { get; set; }

        [XmlElement("IsTreatmentStarted")]
        public bool IsTreatmentStarted { get; set; }

        [XmlElement("TypeOfResistantTBConfirmation")]
        public string TypeOfResistantTBConfirmation { get; set; }

        [XmlElement("HIVStatus")]
        public string HIVStatus { get; set; }

        [XmlArray("PatientDSTDS")]
        [XmlArrayItem("PatientDST")]
        public List<PatientDST> PatientDSTDS { get; set; }

        [XmlElement("PatientHIVTestDS")]
        public List<PatientHIVTest> PatientHIVTestDS { get; set; }

        [XmlElement("PatientDSTAdvancedDS")]
        public List<PatientDSTAdvanced> PatientDSTAdvancedDS { get; set; }

        [XmlElement("PatientSecondLineDrugDS")]
        public List<PatientSecondLineDrug> PatientSecondLineDrugDS { get; set; }

        [XmlElement("PatientSputumDS")]
        public List<PatientSputum> PatientSputumDS { get; set; }
    }

Here is the XML: 这是XML:

<?xml version="1.0" encoding="utf-8"?>
<PatientDS>
  <Patient>
    <PatientID>ED526A85-26E3-424A-B15C-AB32FD114F5E</PatientID>
    <Gender>F</Gender>
    <PatientCategory>N</PatientCategory>
    <SiteOfDisease>PTB</SiteOfDisease>
    <Outcome></Outcome>
    <RegistrationYear>2010</RegistrationYear>
    <RegistrationNo>100</RegistrationNo>
    <RegistrationDate>2010-06-21</RegistrationDate>
    <Name>Jane</Name>
    <Surname>Doe</Surname>
    <IDNumber>7001010099080</IDNumber>
    <BirthDate>1970-01-01</BirthDate>
    <TypeOfResistantTB>MDR</TypeOfResistantTB>
    <TreatmentStartDate>2010-06-21</TreatmentStartDate>
    <OutcomeDate>2010-11-30</OutcomeDate>
    <IsActive>1</IsActive>
    <IsTreatmentStarted>1</IsTreatmentStarted>
    <TypeOfResistantTBConfirmation>LABCONFIRMED</TypeOfResistantTBConfirmation>
    <HIVStatus>P</HIVStatus>
    <PatientDSTDS>
     <PatientDST>
      <TestDate>2010-06-22 08:23:00.000</TestDate>
      <ReferenceNo>NNY0288029</ReferenceNo>
      <PatientDSTDrugDS>
        <PatientDSTDrug>
          <DSTDrug>R</DSTDrug>
          <DSTResult>R</DSTResult>
        </PatientDSTDrug>
        <PatientDSTDrug>
          <DSTDrug>Eto</DSTDrug>
          <DSTResult>S</DSTResult>
        </PatientDSTDrug>
     </PatientDSTDrugDS>
  </PatientDST>
  <PatientDST>
    <PatientDSTID>FBFA09A9-452B-4BA2-BC01-81297EFCC8FD</PatientDSTID>
    <TestDate>2011-07-11 15:50:49.000</TestDate>
    <ReferenceNo>NTH0168507</ReferenceNo>
    <PatientDSTDrugDS>
      <PatientDSTDrug>
        <DSTDrug>R</DSTDrug>
        <DSTResult>R</DSTResult>
      </PatientDSTDrug>
      <PatientDSTDrug>
        <DSTDrug>Eto</DSTDrug>
        <DSTResult>S</DSTResult>
      </PatientDSTDrug>
   </PatientDSTDrugDS>
</PatientDST>
</PatientDSTDS>
<PatientHIVTestDS>
  <PatientHIVTest>
    <HIVTestResult>N</HIVTestResult>
    <TestDate>2010-02-01 00:00:00.000</TestDate>
    <CD4Count>350</CD4Count>
  </PatientHIVTest>
  <PatientHIVTest>
    <HIVTestResult>P</HIVTestResult>
    <TestDate>2010-09-25 00:00:00.000</TestDate>
    <CD4Count>280</CD4Count>
  </PatientHIVTest>
</PatientHIVTestDS>
<PatientDSTAdvancedDS>
  <PatientDSTAdvanced>
    <DSTDrugResult>R</DSTDrugResult>
    <DSTGeneXpertResult>Positive</DSTGeneXpertResult>
    <TestDate>2010-07-11 16:30:00.000</TestDate>
    <ReferenceNo>ABCD9928</ReferenceNo>
  </PatientDSTAdvanced>
  <PatientDSTAdvanced>
    <DSTDrugResult>N</DSTDrugResult>
    <DSTGeneXpertResult>Negative</DSTGeneXpertResult>
    <TestDate>2011-01-18 16:30:00.000</TestDate>
    <ReferenceNo>WXYZ9876</ReferenceNo>
  </PatientDSTAdvanced>
</PatientDSTAdvancedDS>
<PatientSecondLineDrugDS>
  <PatientSecondLineDrug>
    <SecondLineDrug>Ofx</SecondLineDrug>
    <StartDate>2010-09-25 00:00:00.000</StartDate>
  </PatientSecondLineDrug>
  <PatientSecondLineDrug>
    <SecondLineDrug>Bdq</SecondLineDrug>
    <StartDate>2010-10-13 00:00:00.000</StartDate>
  </PatientSecondLineDrug>
</PatientSecondLineDrugDS>
<PatientSputumDS>
  <PatientSputum>
    <SputumResult>R</SputumResult>
    <CultureResult>N</CultureResult>
    <TestDate>2010-06-22 00:00:00.000</TestDate>
    <ReferenceNo>ABC0168503</ReferenceNo>
    <TreatmentMonth>1</TreatmentMonth>
  </PatientSputum>
  <PatientSputum>
    <SputumResult>N</SputumResult>
    <CultureResult>P</CultureResult>
    <TestDate>2010-08-17 00:00:00.000</TestDate>
    <ReferenceNo>XYZ0358503</ReferenceNo>
    <TreatmentMonth>2</TreatmentMonth>
  </PatientSputum>
</PatientSputumDS>

The problem is that I am able to deserialize this object, and all the normal elements are populated with the correct values, but I cannot get the List<> properties to populate. 问题是我可以反序列化此对象,并且所有常规元素都填充有正确的值,但是我无法获取要填充的List <>属性。

What am I doing wrong or missing here? 我在这里做错了什么或想念什么?

Actually when I used the XML and the sample code above it didn't populate any of the fields for me. 实际上,当我使用XML和上面的示例代码时,它并没有为我填充任何字段。 I'm not entirely clear that you're desalinizing into Patient directly but when I added a PatientDS class which is the root in XML it populated all fields including all the lists. 我不清楚您是否直接将其淡化为Patient,但当我添加一个PatientDS类(它是XML的根)时,它填充了包括所有列表在内的所有字段。 I just added this bit: 我刚刚添加了这一点:

public class PatientDS
{
    [XmlElement("Patient")]
    public Patient Patient { get; set; }
}

and I deserialized like this: 我像这样反序列化:

string xml = File.ReadAllText("XMLFile1.xml");
var patient = DeserializeFromXml<PatientDS>(xml); 

and the output seems fine: 和输出似乎很好:

在此处输入图片说明

Hope this was what you were looking for. 希望这就是您想要的。

Try this: 尝试这个:

[XmlRoot(ElementName = "PatientDS")]
public class PatientDS
{
   public Patient Patient { get; set; }
}

[XmlRoot(ElementName = "Patient")]
public class Patient
{
   //stuff
}

And deserialize it. 并反序列化它。

I found the problem. 我发现了问题。

After reading more about reading dates from an XML, I figured the dates provided in the sub items of this XML is not valid (ISO 8601) standard, and therefore my application was struggling to read it, and failed. 在阅读了有关从XML中读取日期的更多信息之后,我发现此XML子项中提供的日期无效(ISO 8601)标准,因此我的应用程序正努力读取它,但失败了。

As this was a dummy XML, I instantiated a new PersonDS object, deserialized it to an XML, and then serialized back to check if the application was working, and it serialized with no problem. 由于这是一个虚拟XML,因此我实例化了一个新的PersonDS对象,将其反序列化为XML,然后进行序列化以检查应用程序是否正常运行,并且进行了序列化。

Thanks all for their help. 谢谢大家的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM