簡體   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