如何基于具有多个子节点的多个条件获得子单记录c# linq或xpath

本文关键字:记录 linq xpath 单记录 何基于 子节点 条件 | 更新日期: 2023-09-27 18:09:18

 var records = (from root in myxmlDoc.Descendants("Root")
                from nts in root.Elements("nts")
                select new
                {
                    Id = (nts.Elements("Id").Any() == true) ? (nts.Element("Id").Value) : string.Empty,
                    Name = (nts.Elements("Name").Any() == true) ? (nts.Element("Name").Value) : string.Empty,
                }).ToList();

我怎么能实现这与<Round>这里<Round>元素将多次不固定计数,也必须采取记录接近动态日期

<Root>
    <nts>
     <Id>A</Id>
     <Name>Rahul</Name>
     <Round>
       <prodDate>2016-03-31</prodDate>
       <roundDue>0.00</roundDue>
     </Round>
     <Round>
       <prodDate>2016-04-01</prodDate>
       <roundDue>400.00</roundDue>
     </Round>
     <Round>
       <prodDate>2016-05-01</prodDate>
       <roundDue>300.00</roundDue>
     </Round>
     <Round>
       <prodDate>2016-08-06</prodDate>
       <roundDue>100.00</roundDue>
     </Round>
     <nts>
     </Root>

我想根据以下标准从多个<Round>元素中获取单个<Round>记录

  1. 1) prodDate小于dynamicDate,即:2016-09-29,roundDue> 0注意:<Round>记录必须是最近的记录,小于dynamicDate即2016-09-29

预期结果:

ID : A;
Name : Rahul
prodDate : 2016-08-06
roundDue : 100.00

此处prodDate必须是动态日期的最近日期,即2016-09-29

如何基于具有多个子节点的多个条件获得子单记录c# linq或xpath

试试这个:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication16
{
    class Program
    {
        const string FILENAME = @"c:'temp'test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            //Note : new DataTime gives a date of 1/1/1900.  Any valid date should be much closer to actual compare date
            var results = doc.Descendants("nts").Select(x => new
            {
                id = (string)x.Element("Id"),
                name = (string)x.Element("Name"),
                round = x.Elements("Round").Select(y => new { prodDate = (object)y.Element("prodDate") == null ? new DateTime() : (DateTime)y.Element("prodDate") , roundDue = (decimal)y.Element("roundDue") })
                   .Where(y => y.roundDue > 0 && y.prodDate < DateTime.Now).OrderBy(y => DateTime.Now - y.prodDate).FirstOrDefault()
            }).FirstOrDefault();
        }
    }
}