理解 Linq To Xml - Descendants 返回没有结果

42

我完全不熟悉Linq2XML,平常为了完成简单的任务编写太多代码,所以在一个简单的项目中我想尝试一下...

我已经花了2个小时,但是什么都做不对 :(

我真的很想回到节点式编码(XmlNode-code-alike)

任务:

  • 我向 ASMX 服务发送一个 SOAP 动作,然后将响应作为 XML 接收
  • 我将 XML 解析成 XDocument 对象
  • 我尝试获取节点列表...问题出现了!

正如您从这个屏幕截图可以看到的那样。

alt文本 http://www.balexandre.com/temp/2010-02-26_0038.png

我的 XDocument 有一个名为TransactionInformationType的节点,它是一个序列,我只想获取所有节点并检索我需要的两个变量(您可以在select c;下面看到代码被注释掉了)。

Watch窗口中,您可以看到

doc.Descendants("TransactionInformationType")

该方法并没有返回任何内容,但是通过文本可视化器中XDocument的内容可以看出该节点确实存在!

有人能解释并帮我解决这个大问题吗?

谢谢!


追加说明

XDocument content


答案

响应XML具有

<gettransactionlistResponse xmlns="https://ssl.ditonlinebetalingssystem.dk/remote/payment">

因此我必须使用此作为命名空间!

事实证明,为了检索值,我确实需要使用XNamespace,因此最终代码如下:

// Parse XML
XDocument doc = XDocument.Parse(strResponse);
XNamespace ns = "https://ssl.ditonlinebetalingssystem.dk/remote/payment";

var trans = from item in doc.Descendants(ns + "TransactionInformationType")
            select new TransactionInformationType
            {
                capturedamount = Convert.ToInt32(item.Element(ns + "capturedamount").Value),
                orderid = item.Element(ns + "cardtypeid").Value
            };
感谢大家的帮助!

1
请您将 XML 的头部发布到您正在查找的元素。这里可能存在命名空间问题。 - AxelEckenberger
完成!将其添加到PasteBin中,因为它很大(即使我只显示了2个交易) :) - balexandre
可能是Xml.Linq: Descendants()返回空值的重复问题。 - Michael Freidgeim
2个回答

49
var result = doc.Descendants("TransactionInformationType");

选择XDocument中所有元素名为"TransactionInformationType"且在空命名空间中的后代。 从您的屏幕截图中看,您要选择的元素似乎位于命名空间"https://ssl.ditonlinebetalingssystem.dk/remote/payment"中。 您需要明确指定:

XNamespace ns = "https://ssl.ditonlinebetalingssystem.dk/remote/payment";
                                              ↑↑                      ↑
var result = doc.Descendants(ns + "TransactionInformationType");

刚刚将XDocument内容添加到我的答案中。如果我使用"https://ssl.ditonlinebetalingsystem.dk/remote/payment/"作为XNamespace,我得到相同的行为...换句话说,仍然没有任何输出 :( - balexandre
@balexandre:在你的示例中,payment 后面没有 /,并且缺少一个 s。确保在 C# 中使用与 XML 示例中完全相同的命名空间。 - dtb
http://www.balexandre.com/temp/2010-02-26_0136.png - balexandre
刚写了一个快速示例,似乎可以工作。http://pastebin.org/97518 如果没有工作,则您的某些方面必须与我不同。 - Joel Lucsy

12

这应该可以解决你的问题(用正确的URL替换命名空间):

XNamespace ns = "https://ssl.ditonline...";
doc.Descendants(ns + "TransactionInformationType");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接