简体   繁体   English

从字符串XML解析?

[英]XML Parsing from the string?

I'm using In App Purchase in my app. 我在我的应用中使用In App Purchase。 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' //存储为字符串“ 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. “ xDoc”始终为空。 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! 请帮助我如何从该xml字符串获取“ PurchasePrice”!

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. 请记住,如果您的xml包含xmlns标记,则该节点及其子节点是该名称空间的一部分。 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 如果您想了解更多关于Wikipedia的文章,那么它是一个很好的起点: http : //en.wikipedia.org/wiki/XML_namespace

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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