简体   繁体   中英

XML Parsing from the string?

I'm using In App Purchase in my app. Here's the Receipt I had after the successful purchase:

<?xml version="1.0"?>
    <Receipt Version="1.0" CertificateId="xxxyyy" xmlns="http://schemas.microsoft.com/windows/2012/store/receipt">
        <ProductReceipt PurchasePrice="$9.99" PurchaseDate="2014-11-18T08:04:37.572Z" ExpirationDate="9999-12-31T00:00:00Z" ProductId="product_id" ProductType="Consumable" AppId="xxx-yyy" Id="xxx-yyy" PublisherDeviceId="xxx-yyy"  PublisherUserId="" MicrosoftProductId="xxx-yyy" MicrosoftAppId="xxx-yyy"  />
    </Receipt>

//stored as the string 'receipt'

I need to display it to the user, But I'm getting error. Here's my code:

var xDoc = XDocument.Parse(receipt).Root.Element("ProductReceipt"); //receipt id the string
string Price = xDoc.Attribute("PurchasePrice").Value; 

'xDoc' is always null. Since it's null, I got an exception on getting price.

Object reference not set to an instance of an object.

Please help me how to get the 'PurchasePrice' from that xml string!

You'll need to use the namespace :

XNamespace ns = "http://schemas.microsoft.com/windows/2012/store/receipt";
var xDoc = XDocument
               .Parse(receipt)
               .Root
               .Element(ns + "ProductReceipt"); //Use namespace ProductReceipt is in

Remember that if your xml contains xmlns markup that node and it's children are part of that namespace. This is to prevent name clashes of elements.

The Wikipedia article is a good starting point if you want to learn more about that: http://en.wikipedia.org/wiki/XML_namespace

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM