我是 LINQ 的新手。我需要为每个 MPrice 返回包含今天日期的正确价格信息的 ID。
这是一个 XML 示例:
<Pricing>
<MPrice>
<Id>0079</Id>
<Price>
<Price>31.25</Price>
<StartDt>2009-8-01</StartDt>
<EndDt>2009-08-26</EndDt>
</Price>
<Price>
<ListPrice>131.25</ListPrice>
<StartDt>2009-08-26</StartDt>
<EndDt>9999-12-31</EndDt>
</Price>
</MPrice>
<MPrice>
<Id>0081</Id>
<Price>
<Price>131.25</Price>
<StartDt>2009-8-01</StartDt>
<EndDt>2009-08-26</EndDt>
</Price>
<Price>
<ListPrice>231.25</ListPrice>
<StartDt>2009-08-26</StartDt>
<EndDt>9999-12-31</EndDt>
</Price>
</MPrice>
</Pricing>
最佳答案
这是一种实现方式:
using System;
using System.Linq;
using System.Xml.Linq;
class Program
{
static void Main()
{
String xml = @"<Pricing>
<MPrice>
<Id>0079</Id>
<Price>
<Price>31.25</Price>
<StartDt>2009-8-01</StartDt>
<EndDt>2009-08-26</EndDt>
</Price>
<Price>
<ListPrice>131.25</ListPrice>
<StartDt>2009-08-26</StartDt>
<EndDt>9999-12-31</EndDt>
</Price>
</MPrice>
</Pricing>";
var priceInfo = from e in XElement.Parse(xml).Elements("MPrice").Elements("Price")
let start = DateTime.Parse(e.Descendants("StartDt").FirstOrDefault().Value)
let end = DateTime.Parse(e.Descendants("EndDt").FirstOrDefault().Value)
where start < DateTime.Now && end > DateTime.Now
select new { Id = e.Parent.Element("Id").Value, ListPrice = e.Element("ListPrice").Value };
Console.WriteLine(priceInfo.FirstOrDefault().Id);
Console.WriteLine(priceInfo.FirstOrDefault().ListPrice);
}
}
输出:
0079
131.25
请注意,需要比本示例提供的更多的错误检查。我会特别添加对日期时间解析的检查(可能通过使用包装 DateTime.TryParseExact
的函数)。
编辑:如果您想使用 XDocument
而不是 XElement
,您需要对查询进行细微更改(注意使用 Descendants
方法代替 Elements
方法):
var priceInfo = from e in XDocument.Parse(xml).Descendants("MPrice").Elements("Price")
let start = DateTime.Parse(e.Descendants("StartDt").FirstOrDefault().Value)
let end = DateTime.Parse(e.Descendants("EndDt").FirstOrDefault().Value)
where start < DateTime.Now && end > DateTime.Now
select new { Id = e.Parent.Element("Id").Value, ListPrice = e.Element("ListPrice").Value };
请记住,您不需要使用 XDocument
除非您将 XML 作为真正的文档来处理。在大多数情况下,XElement
类型就足够了。
编辑#2:如果你想从磁盘加载XDocument
然后使用这个方法:
using System;
using System.Linq;
using System.Xml.Linq;
class Program
{
static void Main()
{
XDocument document = XDocument.Load(@"d:\test.xml");
var priceInfo = from e in document.Descendants("MPrice").Elements("Price")
let start = DateTime.Parse(e.Descendants("StartDt").FirstOrDefault().Value)
let end = DateTime.Parse(e.Descendants("EndDt").FirstOrDefault().Value)
where start < DateTime.Now && end > DateTime.Now
select new { Id = e.Parent.Element("Id").Value, ListPrice = e.Element("ListPrice").Value };
Console.WriteLine(priceInfo.FirstOrDefault().Id);
Console.WriteLine(priceInfo.FirstOrDefault().ListPrice);
}
}
关于c# - 使用 LINQ 解析 XML 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1374586/