繁体   English   中英

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

[英]how to get child single records based on multiple condition having multiple child nodes c# linq or xpath

 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必须是dynamicDate的最近日期,即2016-09-29

尝试这个 :

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

        }
    }
}

暂无
暂无

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

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