XML文件中的子节点

本文关键字:子节点 文件 XML | 更新日期: 2023-09-27 18:14:00

我试图在我的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);
}

My XML File

<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);
}

XML文件中的子节点

问题是您选择了一个数量节点.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);
     }
}
        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);
        }