user1688346
user1688346

Reputation: 1970

LINQ to XML - Null

I have an XML and trying to extract the Login and it didn't work. It always give me null.

<REQUEST xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <LOGIN>
     <USERID>ID</USERID>
     <PASSWORD>12345</PASSWORD>
  </LOGIN>

   XDocument doc = XDocument.Parse(xmlString);
        var login = from x in doc.Root.Elements("REQUEST").Elements("LOGIN")
                    select new login
                    {
                        UserId = x.Element("USERID").Value,
                        Password = x.Element("PASSWORD").Value
                    };
 var loginobject=login.FirstOrDefault();

Upvotes: 1

Views: 85

Answers (3)

Scott Jones
Scott Jones

Reputation: 2908

The Root element is already REQUEST, so you want to jump directly to LOGIN child elements in your query. I got the following working in Linqpad (great tool for testing/developing queries):

string xmlString = @"<REQUEST xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
  <LOGIN>
     <USERID>ID</USERID>
     <PASSWORD>12345</PASSWORD>
  </LOGIN></REQUEST>";

XDocument doc = XDocument.Parse(xmlString);
   var login = from x in doc.Root.Elements("LOGIN")
               select new 
               {
                   UserId = x.Element("USERID").Value,
                   Password = x.Element("PASSWORD").Value
               };
 var loginobject=login.FirstOrDefault();
 loginobject.Dump();

Upvotes: 0

Dave Zych
Dave Zych

Reputation: 21887

When you use doc.Root it gets the root element of the XML doc, which in this case is REQUEST. You then don't want to get the REQUEST element, you want to get the LOGIN element because you're already at the REQUEST node.

Try this:

XDocument doc = XDocument.Parse(xmlString);
var login = from x in doc.Root.Elements("LOGIN")
            select new login
            {
                UserId = x.Element("USERID").Value,
                Password = x.Element("PASSWORD").Value
            };

Upvotes: 2

Mathew Thompson
Mathew Thompson

Reputation: 56429

Your XML is slightly malformed as you have REQUEST as the Root object. Try changing it to something like:

<?xml version="1.0"?>
<REQUEST>
    <LOGIN>
        <USERID>ID</USERID>
        <PASSWORD>12345</PASSWORD>
    </LOGIN>
</REQUEST>

Or if you want to keep your XML the same, just take out the Root.Elements("REQUEST"):

var login = from x in doc.Root.Elements("LOGIN")

Upvotes: 1

Related Questions