Solved

Why do I have trouble using linq on XML with namespaces?

Posted on 2010-08-27
4
741 Views
Last Modified: 2013-11-11
Hello,

I have a class that parses XML from a string and sets the values from the XML to the class properties. I can parse an XML string fine except when a tag has a namespace attribute (xmlns). When I have the namespace included I get an index out of range error on the .ElementAt(0).

An exmaple of _responseXML is

<NetConnectResponse xmlns="http://www.experian.com/NetConnectResponse">
  <CompletionCode>0000</CompletionCode>
  <ReferenceId></ReferenceId>
  <Products xmlns="http://www.experian.com/ARFResponse">
    <CreditProfile>
      <Header>
        <ReportDate>08222010</ReportDate>
        <ReportTime>161300</ReportTime>
        <Preamble>TCA5</Preamble>
        <ARFVersion>07</ARFVersion>
      </Header>
      ...
      ...

Thanks for the help!
-gtar


//load response into XDoc
        xdoc = XDocument.Parse(_responseXML);

 
       //create assimble reportDateTime
        var header = from h in xdoc.Descendants("Header")
                     select new
                     {
                         ReportDate = h.Element("ReportDate").Value,
                         ReportTime = h.Element("ReportTime").Value
                     };

        //set linq vars to local vars
        string rawDate = header.ElementAt(0).ReportDate;
        string rawTime = header.ElementAt(0).ReportTime;

Open in new window

0
Comment
Question by:gtar
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
4 Comments
 
LVL 21

Accepted Solution

by:
chapmanjw earned 500 total points
ID: 33547859
Here is Microsoft's article on using XML namespaces with LINQ: http://msdn.microsoft.com/en-us/library/bb669152.aspx
0
 
LVL 27

Expert Comment

by:nmarun
ID: 33547967
Try something like this:

xdoc = XDocument.Parse(_responseXML);
XNamespace xNamespace = "http://www.experian.com/ARFResponse";

//create assimble reportDateTime
var header = from h in xdoc.Descendants(xNamespace + "Header")
             select new
             {
                   ReportDate = h.Element(xNamespace + "ReportDate").Value,
                   ReportTime = h.Element(xNamespace + "ReportTime").Value
             };

Arun

0
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 33548048
Hi gtar;

I have corrected the code you placed in the question. You have two issues. One is that you need to use the namespace for the nodes that it is assigned to in the XML, see code snippet comments and two the query would never execute because it needs to be enumerated so I added the ToList() which will do the job.

Fernando
//load response into XDoc
xdoc = XDocument.Parse(_responseXML);

// Namespace to be used for child elements off the Root node
// except for the element Products and its child nodes which have 
// another namespace. 
XNamespace rns = "http://www.experian.com/NetConnectResponse";
// Namesapce to be used on the Products element and it child nodes
XNamespace pns = "http://www.experian.com/ARFResponse";

//create assimble reportDateTime
var header = (from h in xdoc.Descendants(pns + "Header")
              select new
              {
                  ReportDate = h.Element(pns + "ReportDate").Value,
                  ReportTime = h.Element(pns + "ReportTime").Value
              }).ToList();

//set linq vars to local vars
string rawDate = header.ElementAt(0).ReportDate;
string rawTime = header.ElementAt(0).ReportTime;

Open in new window

0
 

Author Comment

by:gtar
ID: 33548076
All that was needed for my query to execute was to include the root <NetConnectResponse> namespace in the query.

I was able to execute the query without the toList() method. I'm unclear as to why this is needed. Are you saying that if I had several <Header> values that the ToList would ad them to a list and that my original query would not?

Thanks for all your help!

I awarded chapmanjw with the points because I read the suggested msdn article and resolved my problem before I saw the rest of the posts.

Do you have a better approach to accessing the header data. It seems awkward to do the following

header.ElementAt(0).ReportDate

Thanks again,
Gtar

        XNamespace xNamespace = "http://www.experian.com/NetConnectResponse";

        //create assimble reportDateTime
        var header = from h in xdoc.Descendants(xNamespace + "Header")
                     select new
                     {
                         ReportDate = h.Element(xNamespace + "ReportDate").Value,
                         ReportTime = h.Element(xNamespace + "ReportTime").Value
                     };

Open in new window

0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Creating an element based on double condition with XSLT 9 37
asp.net repeater 2 36
Difference between Leaflet and MapBox? 5 45
Run software updates from the website 6 50
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question