c# - 使用 XDocument 查找元素属性

标签 c# xml xml-parsing linq-to-xml

我正在尝试从以下 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") 为空。为什么 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;

关于c# - 使用 XDocument 查找元素属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16657407/

相关文章:

c# - 将 Jalali 月份添加到 Jalali 日期

c# - Linq 从属性符合条件的列表中选择

python - 将 .CSV 文件转换为 .XML

java - 如何设置 OnClickListener (Android)

C#:WinRT 中的托管扩展性框架

c# - C# 生成的 Excel 工作表中的自动调整列宽

xml - 查找并替换为唯一

xml - 使用 R 的 xmlEventParse 存储 XML 节点值以进行过滤输出

python - 如何获取 cElementTree 中元素的所有文本子项?

jakarta-ee - 解析 XSL 文件时出错