Understanding Linq To Xml - Descendants return no results

balexandre picture balexandre · Feb 26, 2010 · Viewed 16.5k times · Source

I'm a completly New to Linq2XML as I code to much lines to perform simple things, and in a simple project I wanted to give it a try...

I'm with this for 2 hours and nothing I do get's it right :(

I'm really, really thinking to go back to XmlNode-code-alike

The Task:

  • I send a SOAP Action to an ASMX service and I get the response as XML
  • I Parse the XML into a XDocument object
  • I try to get a list of nodes ... err! Problem!

as you can see from this screenshot

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

my XDocument has a Node called TransactionInformationType witch is a Sequence, and I simple want to get all and retrieve the only 2 variables that I need (you can see the code commented) just below select c;

in the Watch window you can see that

doc.Descendants("TransactionInformationType")

returns nothing at all, and seeing by the content of the XDocument in the Text Visualizer, it does exist!

Anyone care to explain and help me passing this HUGE wall?

Thank you!


Added

XDocument content


Answer

the Response XML has

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

and I must use this as Namespace!

turns out that, to retrieve values, I do need to use the XNamespace as well, so the final code looks like this:

// 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
            };

Thank you all for the help!

Answer

dtb picture dtb · Feb 26, 2010
var result = doc.Descendants("TransactionInformationType");

selects all descendants in the XDocument that have element name "TransactionInformationType" and are in the empty namespace. From you screenshot it seems the element you're trying to select is in the namespace "https://ssl.ditonlinebetalingssystem.dk/remote/payment" though. You need to specify that explicitly:

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