6

次の XML 構造 (Windows Phone のアプリ内購入からの領収書) から PurchaseDate を取得しようとしています。

<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 要素を取得しないのはなぜですか?

4

1 に答える 1

10

名前空間を 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;
于 2013-05-20T20:05:26.203 に答える