使用LINQ解析收据XML [英] Parsing Receipt XML with LINQ

查看:97
本文介绍了使用LINQ解析收据XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个使用商店购买的Windows应用商店应用程序.购买后,将返回一些XML.我正在尝试查看用户是否成功购买了该产品.我知道我可以使用LINQ来确定这一点,但是我不确定如何编写LINQ查询.

I'm working on a Windows Store app that uses in-store purchases. When a purchase is made, some XML is returned. I'm trying to see if the user successfully purchased the product. I know I can determine this with LINQ, but I'm not sure how to write my LINQ query.

private bool WasProductPurchasedFromStore(string productName)
{
        string data = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Receipt Version=\"1.0\" ReceiptDate=\"2012-11-24T12:22:20Z\" CertificateId=\"\" ReceiptDeviceId=\"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa\"><ProductReceipt Id=\"bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb\" AppId=\"MyNamespace.MyApp_t7396xywk1mky\" ProductId=\"Upgrade\" PurchaseDate=\"2012-11-24T12:22:20Z\" ProductType=\"Durable\"  /></Receipt>";
  XDocument xml = XDocument.Parse(data);

  // Return true if the productName is found in the XML.
  // THIS IS WHERE I'M STUCK
  var result = from receipt in xml
               select receipt;

  // Return false if the user did not make the purchase
  return false;
}

如何查询xml以查看是否有ProductReceipt元素的ProductId属性值与productName中的值匹配?

How do I query my xml to see if there is a ProductReceipt element that has a ProductId attribute value that matches the value in productName?

谢谢您的帮助!

推荐答案

如果您始终知道元素和属性将存在,​​请尝试以下方法:

Try like this if you always know that the element and attribute will be there:

bool result = xml.Descendants("ProductReceipt")
    .Attributes().Single(x => x.Name == "ProductId")
    .Value == productName;

如果元素和属性可能丢失,则可以执行SingleOrDefault并对每个步骤进行空检查

If the elements and attributes can be missing you can do SingleOrDefault and null check each step

这篇关于使用LINQ解析收据XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆