0

我遇到了一个烦人的小错误,我一生都无法弄清楚为什么会这样。我有一个用于存储数据的 xml 文件,如下所示。

- <EmployeeFinance>
  <EmployeeEmploy_Id>5584</EmployeeEmploy_Id> 
  <EmpPersonal_Id>30358</EmpPersonal_Id> 
  <No_DaysWorked>30</No_DaysWorked> 
  <Date_Appointment>17/02/2012</Date_Appointment> 
  <Date_Employment>02/05/1984</Date_Employment> 
  <Date_Termination>01/01/0001</Date_Termination> 
  <Payperiod_StartDate>01/01/2013</Payperiod_StartDate> 
  <Payperiod_EndDate>31/01/2013</Payperiod_EndDate> 
  <BatchNumber>38</BatchNumber> 
  <PAYE_ToDate_Computed>0</PAYE_ToDate_Computed> 
  <Income_Tax_RateID>0</Income_Tax_RateID> 
  <NIS_RateID>0</NIS_RateID> 
  <NIS_weeks_worked>0</NIS_weeks_worked> 
  </EmployeeFinance>

如果您查看日期节点,Payperiod_StartDate、Payperiod_EndDate、Date_Appointment 等。它们都具有相同的格式。现在在我的 C# 代码中,当我编写查询以从 xml 文件中选择时,我得到String 未被识别为有效的 DateTime错误。当我注释掉所有其他日期并离开 start_date 时,它​​可以工作。它们是相同的格式,我看不出我做错了什么。请帮我。

    var context = new SSPModel.sspEntities();
    XElement xelement = XElement.Load(GlobalClass.GlobalUrl);
    XDocument doc = XDocument.Load(GlobalClass.GlobalUrl);

    var query = from nm in xelement.Elements("EmployeeFinance")
                select new EmployeeEmploy
                {
                    Employee_Personal_InfoEmp_id = (int)nm.Element("EmpPersonal_Id"),
                    Substantive_designation = (int)nm.Element("Position_Id"),
                    Grade_Id = (int)nm.Element("Grade_Id"),
                    PositionTotal_PtBasic = (double)nm.Element("Sum_AllPosition"),//part of basic
                    GradeTotal_PtBasic = (double)nm.Element("Sum_AllGrade"), //part of basic
                    Housing_Allowance = (double)nm.Element("Housing"),
                    Base_Pay = (double)nm.Element("Base_Pay"),
                    startDate = (DateTime)nm.Element("Payperiod_StartDate"),
                    endDate = (DateTime)nm.Element("Payperiod_EndDate"),
                    Date_of_Appointment = (DateTime)nm.Element("Date_Appointment"),
                   Date_of_Employment = (DateTime)nm.Element("Date_Employment"),
                    Termination_date_actual = (DateTime)nm.Element("Date_Termination"),
                    Base_Pay_Currency = (string)nm.Element("Currency"),
                    Exchange_rate = (double)nm.Element("Exchange_Rate")
                };
    var x = query.ToList();
    foreach (var xy in x) {
        Debug.WriteLine(xy.endDate);
    }
4

2 回答 2

1

因为17/02/2012不是一个有效的日期,但是,02/17/2012是。日期将被解析为mm/dd/yyyy. 一种选择是使用DateTime.ParseExact来解析日期,其中ddd作为第一组数字。例如

var startDate = DateTime.ParseExact("17/02/2012", "dd/MM/yyyy", null);
于 2013-06-10T14:37:04.853 回答
0

The debugger will show you that nm.Element("Payperiod_EndDate").ToString() gives you a string that includes the xml tags for that element. Try the following instead:

startDate = DateTime.ParseExact(nm.Element("Payperiod_EndDate").Value, "dd/MM/yyyy", null)

于 2013-06-10T16:28:46.023 回答