我正在尝试从以下
XML结构获取PurchaseDate(来自
Windows Phone中的应用内购买的收据):
<Receipt Version="1.0" CertificateId="..." xmlns="http://schemas.microsoft.com/windows/2012/store/receipt"> <ProductReceipt PurchasePrice="$0" PurchaseDate="2013-05-20T19:27:09.755Z" Id="..." AppId="..." ProductId="Unlock" ProductType="Consumable" PublisherUserId="..." Publisherdeviceid="..." MicrosoftProductId="..." /> <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> <SignedInfo> <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /> <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" /> <Reference URI=""> <Transforms> <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /> </Transforms> <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" /> <DigestValue>...</DigestValue> </Reference> </SignedInfo> <SignatureValue>...</SignatureValue> </Signature> </Receipt>
我的代码如下:
XDocument doc = XDocument.Parse(receiptXml); string date = doc.Root.Element("ProductReceipt").Attribute("PurchaseData").Value;
这会不断引发访问错误,因为doc.Root.Element(“ProductReceipt”)为null.为什么XDocument没有获得ProductReceipt元素?
解决方法
只需将命名空间添加到LINQ to XML查询中即可.因为您在根节点xmlns =“http://schemas.microsoft.com/windows/2012/store/receipt”上有默认名称空间声明,所以您还需要在查询中指定它.
XDocument doc = XDocument.Parse(receiptXml); XNamespace xmlns = "http://schemas.microsoft.com/windows/2012/store/receipt"; string date = doc.Root .Element(xmlns + "ProductReceipt") .Attribute("PurchaseDate") .Value; Console.WriteLine(date);
打印:
2013-05-20T19:27:09.755Z
string date = doc.Root .Elements() .First(node => node.Name.LocalName == "ProductReceipt") .Attribute("PurchaseDate") .Value;
原文地址:https://www.jb51.cc/csharp/244983.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。