简体   繁体   English

从Xml文件读取到现有数据表C#ASP.NET Core

[英]Reading from Xml FIle into existing dataTable C# ASP.NET Core

Here is the method where I have the problem: 这是我遇到问题的方法:

[HttpPost]
    public async Task<IActionResult> XmlPage(IFormFile xmlFile)
    { 
      var uploads = hostingEnvironment.WebRootPath;
        if (xmlFile.ContentType.Equals("application/xml") || xmlFile.ContentType.Equals("text/xml"))
        {
            try
            {
                using (var fileStream = new FileStream(Path.Combine(uploads, xmlFile.FileName), FileMode.Create))
                {
                    await xmlFile.CopyToAsync(fileStream);
                    XDocument xDoc = XDocument.Load(fileStream);
                    List<DmgRegister> dmgRegistterList = xDoc.Descendants("Claim").Select(dmgReg =>
                    new DmgRegister
                    {
                        Uwyear = dmgReg.Element("UWYear").Value,
                        ClaimNo = dmgReg.Element("ClaimNo").Value,
                        PolicyNo = dmgReg.Element("PolicyNo").Value,
                        PolicyName = dmgReg.Element("PolicyHolder").Value,
                        Address1 = dmgReg.Element("Address1").Value,
                        Address2 = dmgReg.Element("Addresstype").Value,
                        PostalLocation = dmgReg.Element("City").Value,
                        Country = dmgReg.Element("Country").Value,
                        PostalCode = dmgReg.Element("Postalzone").Value
                    }).ToList();
                    context.SaveXmlToDb(dmgRegistterList);

            }
            catch
            {
//Here where i come when i try to upload and parse the data
                ViewBag.Error = "Converting fail";
                return View("Export");
            }
        }
        else
        {
            ViewBag.Error = "Uploading fail";
            return View("Index");
        }
        return View();
    }

Im trying to upload an xml file and then parse into a SQL Table(Sql DataTable named DmgRegister), I'm a beginner with ASP.Net so exuse me if the code looks like an italian spaghetti. 我试图上传一个xml文件,然后解析为一个SQL表(名为DmgRegister的SQL数据表),我是ASP.Net的初学者,所以如果代码看起来像意大利面条,请原谅我。

       // SaveXmlToDb method in context 
          foreach (var item in dmgRegistterList)
            {
                DmgRegister.Add(item);
            }
        SaveChanges();
                }

Now the Model that I'm trying to bind data from XML and save it to DataTable 现在,我正在尝试从XML绑定数据并将其保存到DataTable的Model

 [Serializable]
[XmlRoot("Claims")]
public class Claim
{
    [XmlElement("ClientName")]
    public string ClientName { get; set; }
    [XmlElement("UWYear")]
    public string Uwyear { get; set; }
    [XmlElement("AgreementNo")]
    public string AgreementNo { get; set; }
    [XmlElement("BusinessType")]
    public string BusinessType { get; set; }
    [XmlElement("PeriodStart")]
    public DateTime? PeriodStart { get; set; }
    [XmlElement("PeriodEnd")]
    public DateTime? PeriodEnd { get; set; }
    [XmlElement("PolicyNo")]
    public string PolicyNo { get; set; }
    [XmlElement("PolicyHolder")]
    public string PolicyName { get; set; }
    [XmlElement("DateOfLoss")]
    public DateTime? DateOfLoss { get; set; }
    [XmlElement("ClaimNo")]
    public string ClaimNo { get; set; }
    [XmlElement("ClaimantName")]
    public string ClaimantName { get; set; }
    [XmlElement("ClaimedInsured")]
    public string ClaimedInsured { get; set; }
    [XmlElement("ReportDate")]
    public DateTime? ReportDate { get; set; }
    [XmlElement("CountryOfRisk")]
    public string CountryOfRisk { get; set; }
    [XmlElement("CountryOfLoss")]
    public string CountryOfLoss { get; set; }
    [XmlElement("TypeOfLoss")]
    public string TypeOfLoss { get; set; }
    [XmlElement("InsuranceCoverage")]
    public string InsuranceCoverage { get; set; }
    [XmlElement("LineOfBuisnessNo")]
    public int? LineOfBuisnessNo { get; set; }
    [XmlElement("LineOfBuisnessName")]
    public string LineOfBuisnessName { get; set; }
    [XmlElement("ClassOfBuisnessNo")]
    public int? ClassOfBuisnessNo { get; set; }
    [XmlElement("ClassOfBuisnessName")]
    public string ClassOfBuisnessName { get; set; }
    [XmlElement("CaptiveShare")]
    public int? CaptiveShare { get; set; }
    [XmlElement("OriginalCurrency")]
    public string OriginalCurrency { get; set; }
    [XmlElement("PaymentCurrency")]
    public string PaidInCurrency { get; set; }
    [XmlElement("TotalIncurredCaptiveShare")]
    public decimal? TotalIncurredCaptiveShare { get; set; }
    [XmlElement("PaidThisPeriod")]
    public decimal? PaidThisPeriod { get; set; }
    [XmlElement("PeriodDate")]
    public DateTime? PeriodDate { get; set; }
    [XmlElement("PaymentDate")]
    public DateTime? PaymentDate { get; set; }
    [XmlElement("TotalPaidCaptiveShare")]
    public decimal? TotalPaidCaptiveShare { get; set; }
    [XmlElement("RemainingReserveCaptiveShare")]
    public decimal? RemainingReserveCaptiveShare { get; set; }
    [XmlElement("Deductible")]
    public string Deductible { get; set; }
    [XmlElement("Recovery")]
    public string Recovery { get; set; }
    [XmlElement("LocationAdress")]
    public string LocationAdress { get; set; }
    [XmlElement("Address1")]
    public string Address1 { get; set; }
    [XmlElement("Addresstype")]
    public string Address2 { get; set; }
    [XmlElement("Postalzone")]
    public string PostalCode { get; set; }
    [XmlElement("City")]
    public string PostalLocation { get; set; }
    [XmlElement("Country")]
    public string Country { get; set; }
    [XmlElement("GeograficalDiversification")]
    public string GeograficalDiversification { get; set; }
    [XmlElement("Cause")]
    public string Cause { get; set; }
    [XmlElement("Status")]
    public string Status { get; set; }
    [XmlElement("CloseDate")]
    public DateTime? CloseDate { get; set; }
    [XmlElement("DevelopmentYear")]
    public string DevelopmentYear { get; set; }
    [XmlElement("TotalIncurredInsurerShare")]
    public decimal? TotalIncurredInsurerShare { get; set; }
    [XmlElement("TotalPaidInsurerShare")]
    public decimal? TotalPaidInsurerShare { get; set; }
    [XmlElement("RemainingReserveInsurerShare")]
    public decimal? RemainingReserveInsurerShare { get; set; }

}
[Serializable()]
[XmlRoot("Claims")]
public class Claims
{
    [XmlArray("Claims")]
    [XmlArrayItem("Claim", typeof(Claim))]
    public Claim[] Claim { get; set; }
}

Here is the Xml example that im try upload 这是我尝试上传的Xml示例

<ns0:Claims>
<Claim>
<ClaimNo>LL0000110262</ClaimNo>
<PolicyNo>LP0000004481</PolicyNo>
<PolicyHolder>NCC Rakennus Oy</PolicyHolder>
<AddressId>1</AddressId>
<Address1>Example Street 1</Address1>
<Addresstype>LocationOfLoss</Addresstype>
<City>Helsinki</City>
<Country>FI</Country>
<Postalzone>12345</Postalzone>
<UWYear>2015</UWYear>
<PeriodStart>2015-01-01</PeriodStart>
<PeriodEnd>2015-12-31</PeriodEnd>
<DateOfLoss>2015-07-15</DateOfLoss>
<ReportDate/>
<StatusAsPer>2015-12-31</StatusAsPer>
<Coverage>?</Coverage>
<TypeOfLoss>Leakage</TypeOfLoss>
<OriginalCurrency>EUR</OriginalCurrency>
<PaymentCurrency>EUR</PaymentCurrency>
<TotalReservesOrigCurr>0.00</TotalReservesOrigCurr>
<TotalPaymentOrigCurr>0.00</TotalPaymentOrigCurr>
<DeductibleOrigCurr>85000.00</DeductibleOrigCurr>
<TotalAmountOfClaimOrigCurr>3680.00</TotalAmountOfClaimOrigCurr>
<Status>Active</Status>
</Claim>
</ns0:Claims>

I try it even to convert from XML to JSON, but it jumps to catch 我什至尝试将其从XML转换为JSON,但是它跳了起来

        public async Task<IActionResult> XmlPage(IFormFile xmlFile)
    {
        var uploads = hostingEnvironment.WebRootPath;
        var filePath = Path.Combine(uploads, xmlFile.FileName);
        if (xmlFile.ContentType.Equals("application/xml") || xmlFile.ContentType.Equals("text/xml"))
        {
            try
            {
                    using (var xReader = XmlReader.Create(new StringReader(filePath)))
                    {
                        // This line skips the XML declaration, eg "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" - you can skip this if you don't have declaration as in your case
                        xReader.MoveToContent();
                        // Gets the actual XMLElement, if any
                        xReader.Read();
                        // Convert the xReader to an XNode for the Json serializer
                        XNode node = XNode.ReadFrom(xReader);
                        // Json output
                        string jsonText = JsonConvert.SerializeXNode(node);



                }
            }
            catch
            {
                ViewBag.Error = "Converting fail";
                return View("Export");
            }
        }
        else
        {
            ViewBag.Error = "Uploading fail";
            return View();
        }
        return View("Index");
    }

Given you are getting a "Root element is missing" this looks like an issue with your mapping. 鉴于您遇到“缺少根元素”的情况,这看起来像是映射问题。

[XmlRoot("Claims")] will not map onto <ns0:Claims> . [XmlRoot("Claims")]不会映射到<ns0:Claims>

Try updating your XML so the roots element is set to <Claims></Claims> rather than 尝试更新XML,以便将roots元素设置为<Claims></Claims>而不是

<ns0:Claims></ns0:Claims> . <ns0:Claims></ns0:Claims>

If this fixes it then you can either change your XML or update your attribute in the class so it looks like this. 如果此问题得以解决,则您可以更改XML或更新类中的属性,使其看起来像这样。

[XmlRoot("ns0:Claims")] . [XmlRoot("ns0:Claims")]

Thx a lot CountZero, really gratefull after my first question here, still had issues but now is everything working, The method in controller 非常感谢CountZero,我在这里提出第一个问题后真的很高兴,仍然有问题,但是现在一切正常,控制器中的方法

       public async Task<IActionResult> XmlPage(IFormFile xmlFile)
    {
        var uploads = hostingEnvironment.WebRootPath;
        var filePath = Path.Combine(uploads, xmlFile.FileName).ToString();

        if (xmlFile.ContentType.Equals("application/xml") || xmlFile.ContentType.Equals("text/xml"))
        {
            try
            {
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    await xmlFile.CopyToAsync(fileStream);
                    fileStream.Dispose();
                    XDocument xDoc = XDocument.Load(filePath);
                    List<DmgRegisterVM> dmgRegistterList = xDoc.Descendants("Claim").Select(dmgReg =>
                    new DmgRegisterVM
                    {
                        Uwyear = dmgReg.Element("UWYear").Value,
                        ClaimNo = dmgReg.Element("ClaimNo").Value,
                        PolicyNo = dmgReg.Element("PolicyNo").Value,
                        PolicyName = dmgReg.Element("PolicyHolder").Value,
                        Address1 = dmgReg.Element("Address1").Value,
                        Address2 = dmgReg.Element("Addresstype").Value,
                        PostalLocation = dmgReg.Element("City").Value,
                        Country = dmgReg.Element("Country").Value,
                        PostalCode = dmgReg.Element("Postalzone").Value
                    }).ToList();
                    context.SaveXmlToDb(dmgRegistterList);
                }
            }
            catch(Exception e)
            {
                    ViewBag.Error = "Converting fail";
            }
        }
        else
        {
            ViewBag.Error = "Uploading fail";
        }
        return View("Index");
    }

SaveXmlToDb method in context 上下文中的SaveXmlToDb方法

        public void SaveXmlToDb(List<DmgRegisterVM> dmgRegList)
    {
        //from list to database
        foreach (var item in dmgRegList)
        {
            var model = Mapper.Map<DmgRegister>(item);
            DmgRegister.Add(model);
            SaveChanges();         
        }
    }

And finally the Claim class (where i have XML elements) 最后是Claim类(其中有XML元素)

 [Serializable]
[XmlRoot("ns0:Claims")]
public class Claim
{
    [XmlElement("ClientName")]
    public string ClientName { get; set; }
    [XmlElement("UWYear")]
    public string Uwyear { get; set; }
    [XmlElement("AgreementNo")]
    public string AgreementNo { get; set; }
    [XmlElement("BusinessType")]
    public string BusinessType { get; set; }
    [XmlElement("PeriodStart")]
    public DateTime? PeriodStart { get; set; }
    [XmlElement("PeriodEnd")]
    public DateTime? PeriodEnd { get; set; }
    [XmlElement("PolicyNo")]
    public string PolicyNo { get; set; }
    [XmlElement("PolicyHolder")]
    public string PolicyName { get; set; }
    [XmlElement("DateOfLoss")]
    public DateTime? DateOfLoss { get; set; }
    [XmlElement("ClaimNo")]
    public string ClaimNo { get; set; }
    [XmlElement("ClaimantName")]
    public string ClaimantName { get; set; }
    [XmlElement("ClaimedInsured")]
    public string ClaimedInsured { get; set; }
    [XmlElement("ReportDate")]
    public DateTime? ReportDate { get; set; }
    [XmlElement("CountryOfRisk")]
    public string CountryOfRisk { get; set; }
    [XmlElement("CountryOfLoss")]
    public string CountryOfLoss { get; set; }
    [XmlElement("TypeOfLoss")]
    public string TypeOfLoss { get; set; }
    [XmlElement("InsuranceCoverage")]
    public string InsuranceCoverage { get; set; }
    [XmlElement("LineOfBuisnessNo")]
    public int? LineOfBuisnessNo { get; set; }
    [XmlElement("LineOfBuisnessName")]
    public string LineOfBuisnessName { get; set; }
    [XmlElement("ClassOfBuisnessNo")]
    public int? ClassOfBuisnessNo { get; set; }
    [XmlElement("ClassOfBuisnessName")]
    public string ClassOfBuisnessName { get; set; }
    [XmlElement("CaptiveShare")]
    public int? CaptiveShare { get; set; }
    [XmlElement("OriginalCurrency")]
    public string OriginalCurrency { get; set; }
    [XmlElement("PaymentCurrency")]
    public string PaidInCurrency { get; set; }
    [XmlElement("TotalIncurredCaptiveShare")]
    public decimal? TotalIncurredCaptiveShare { get; set; }
    [XmlElement("PaidThisPeriod")]
    public decimal? PaidThisPeriod { get; set; }
    [XmlElement("PeriodDate")]
    public DateTime? PeriodDate { get; set; }
    [XmlElement("PaymentDate")]
    public DateTime? PaymentDate { get; set; }
    [XmlElement("TotalPaidCaptiveShare")]
    public decimal? TotalPaidCaptiveShare { get; set; }
    [XmlElement("RemainingReserveCaptiveShare")]
    public decimal? RemainingReserveCaptiveShare { get; set; }
    [XmlElement("Deductible")]
    public string Deductible { get; set; }
    [XmlElement("Recovery")]
    public string Recovery { get; set; }
    [XmlElement("LocationAdress")]
    public string LocationAdress { get; set; }
    [XmlElement("Address1")]
    public string Address1 { get; set; }
    [XmlElement("Addresstype")]
    public string Address2 { get; set; }
    [XmlElement("Postalzone")]
    public string PostalCode { get; set; }
    [XmlElement("City")]
    public string PostalLocation { get; set; }
    [XmlElement("Country")]
    public string Country { get; set; }
    [XmlElement("GeograficalDiversification")]
    public string GeograficalDiversification { get; set; }
    [XmlElement("Cause")]
    public string Cause { get; set; }
    [XmlElement("Status")]
    public string Status { get; set; }
    [XmlElement("CloseDate")]
    public DateTime? CloseDate { get; set; }
    [XmlElement("DevelopmentYear")]
    public string DevelopmentYear { get; set; }
    [XmlElement("TotalIncurredInsurerShare")]
    public decimal? TotalIncurredInsurerShare { get; set; }
    [XmlElement("TotalPaidInsurerShare")]
    public decimal? TotalPaidInsurerShare { get; set; }
    [XmlElement("RemainingReserveInsurerShare")]
    public decimal? RemainingReserveInsurerShare { get; set; }

}
//[ModelMetadataType(typeof(DmgRegisterMetaData))]
[Serializable()]
[XmlRoot("ns0:Claims")]
public class ClaimsCollection
{
    [XmlArray("Claims")]
    [XmlArrayItem("Claim", typeof(Claim))]
    public Claim[] Claim { get; set; }
}

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

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