0

我试图在我的 xml 文件中获取子节点并将其打印出来..但是我不能。它只是打印一个元素而不是全部。请帮忙。

XDocument doc = XDocument.Load(GlobalClass.GlobalUrl);
XElement xelement = XElement.Load(GlobalClass.GlobalUrl);

var query = from nm in xelement.Elements("EmployeeFinance")
            where (int)nm.Element("EmpPersonal_Id") == empID
            select new AllowancePaid
            {
                Income_ID = (decimal)nm.Element("Allowance-Grade")
                                       .Element("Amount")
            };

var x = query.ToList();

foreach (var ele in x) {
    Debug.WriteLine(ele.Income_ID);
}

我的 XML 文件

<EmployeeFinance>
  <EmployeeEmploy_Id>4891</EmployeeEmploy_Id> 
  <EmpPersonal_Id>28407</EmpPersonal_Id> 
  <Employee_Number>11715</Employee_Number> 
  <Allowance-Grade>
    <Amount BenListID="32">6000.00</Amount> 
    <Amount BenListID="59">100000.00</Amount> 
  </Allowance-Grade>
</EmployeeFinance>

添加元素

var result = from element in doc.Descendants("EmployeeFinance")
             where int.Parse(element.Element("EmpPersonal_Id").Value) == tt.Employee_Personal_InfoEmp_id
             select element;
foreach (var ele in result)
{                                      
    ele.Element("Allowance-Grade")
       .Add(new XElement("Amount", new XAttribute("BenListID", tt.ID), tt.Amount));
    doc.Save(GlobalClass.GlobalUrl);
}
4

2 回答 2

2

问题是您选择了一个数量节点.Element("Amount"),但有很多节点。将其更改为.Elements("Amount")需要更改的地方很少。我还没有测试过,但逻辑应该像下面这样可以工作`

var query = from nm in xelement.Elements("EmployeeFinance")
            where (int)nm.Element("EmpPersonal_Id") == empID
            select new AllowancePaid
            {
                AllowanceList = nm.Element("Allowance-Grade").Elements("Amount").Select( a=>(decimal)a.Value).ToList()

            };

foreach (var ele in query) {
    foreach (var a in ele.AllowanceList) {
      Debug.WriteLine(a);
     }
}
于 2013-05-17T14:36:42.260 回答
0
        XDocument xelement = XDocument.Parse(xml);

        var query = from nm in xelement.Elements("EmployeeFinance")
                    where (int)nm.Element("EmpPersonal_Id") == 28407
                    select new
                    {
                        Amounts = nm.Element("Allowance-Grade")
                                               .Elements("Amount")
                                               .Select(
                                               row =>
                                                   new {
                                                        id = row.Value
                                                   }
                                               ).ToList()
                    };

        var x = query.ToList();

        foreach (var ele in x)
        {
            foreach(var a in ele.Amounts)
                Console.WriteLine(a);
        }
于 2013-05-17T14:57:52.993 回答