Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Linq To Xml - Descendants return no results

Tags:

c#

linq-to-xml

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!

like image 221
balexandre Avatar asked Feb 25 '10 23:02

balexandre


2 Answers

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"); 
like image 66
dtb Avatar answered Oct 08 '22 19:10

dtb


This should solve you isssue (replace the namespace with the right URL):

XNamespace ns = "https://ssl.ditonline..."; doc.Descendants(ns + "TransactionInformationType"); 
like image 34
AxelEckenberger Avatar answered Oct 08 '22 18:10

AxelEckenberger