需要帮助来反序列化XML数据

时间:2015-10-19 15:55:18

标签: c# xml deserialization

我正在尝试使用C#

反序列化以下XML
 <?xml version="1.0" encoding="utf-8"?>
 <Invoice>
 <Samples>
 <Sample>
   <AccountId>1e547ae6-9a6d-d18f-958b-22000b83a845</AccountId>
   <AccountNumber>55761598808</AccountNumber>
 </Sample>
 <Sample>
  <AccountId>1e547ae6-9a6d-d18f-958b-22000b83a845</AccountId>
  <AccountNumber>55761598808</AccountNumber>
 </Sample>
 </Samples>
</Invoice>

以下是我为反序列化定义的类

         [DataContract(Name = "Sample")]
         public class Sample
         {
             [DataMember(Name = "AccountId")]
             public string AccountId { get; set; }
             [DataMember(Name = "AccountNumber")]
             public string AccountNumber { get; set; }
         }

         [DataContract(Name = "Samples")]
         public class Samples
         {
             [DataMember(Name = "Sample")]
             public List<Sample> Sample { get; set; }
         }

         [DataContract(Name = "Invoice")]
         public class Invoice
         {
             [DataMember(Name = "Samples")]
             public Samples Samples { get; set; }
         }

反序列化的相应测试用例如下

  public void SampleXmlTest()
    {
        dynamic env = SUT.GetEnvironment();

       string dbConnStrUrjanet = (string)env.AvidUtility.UrjanetDB;
    XmlSerializer deserializer = new XmlSerializer(typeof(CommonAvidXmlDto.Invoice));

        TextReader reader = new StreamReader(@"C:\Users\SJuluru\Desktop\Sample XML\Samplexml.xml");

        Object obj = deserializer.Deserialize(reader);

        CommonAvidXmlDto.Invoice XmlData4 = (CommonAvidXmlDto.Invoice)obj;

运行测试用例调试模式后,XmlData4在没有XML数据的情况下为null。请帮助我修改此代码以便工作。

2 个答案:

答案 0 :(得分:0)

DataContractDataMemberDataContractSerializer的属性,因此您应该替换序列化程序msdn或使用XmlSerializer的属性({{1}等等)

答案 1 :(得分:0)

更改反序列化类:

using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace ConsoleApp4
{
    [XmlRoot(ElementName = "Sample")]
    public class Sample
    {
        [XmlElement(ElementName = "AccountId")]
        public string AccountId { get; set; }
        [XmlElement(ElementName = "AccountNumber")]
        public string AccountNumber { get; set; }
    }

    [XmlRoot(ElementName = "Samples")]
    public class Samples
    {
        [XmlElement(ElementName = "Sample")]
        public List<Sample> Sample { get; set; }
    }

    [XmlRoot(ElementName = "Invoice")]
    public class Invoice
    {
        [XmlElement(ElementName = "Samples")]
        public Samples Samples { get; set; }
    }
}

使用以下方法反序列化:

private static Invoice LoadInvoice(string fileName)
{
    var serializer = new XmlSerializer(typeof(Invoice));

    if (!File.Exists(fileName))
    {
        return null;
    }
    using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        return (Invoice)serializer.Deserialize(fs);
    }
}

结果:

enter image description here