Click here to Skip to main content
15,943,008 members
Please Sign up or sign in to vote.
3.67/5 (3 votes)
See more:
C#
var loadv = XDocument.Load("C:/Users/DELL/Desktop/test.xml").ToString();
            var xDocv = XDocument.Parse(loadv);
            string NbV = xDocv.Descendants("UserName").First().Value;


I encountered an error "Sequence contains no elements" , this my xml file and I dont know why the sequence contains no element.
however "xDocv" contains the xml sequence

XML
<?xml version="1.0" encoding="utf-8"?>
<QueriesResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Jobs xmlns="http://schemas.monster.com/Monster">
    <Job allowExpiredUpdates="false" enforceUniqueness="true" inventoryType="transactional" jobComplete="true" jobRefCode="testtest">
      <RecruiterReference userId="204841377">
        <UserName>xrtpjobsx01</UserName>
        <PersonName>
          <GivenName>Monster</GivenName>
          <FamilyName>Testing</FamilyName>
        </PersonName>
        <EmailAddress>test@test.com</EmailAddress>
      </RecruiterReference>





There is someone who can check this with me ?
Posted

1 solution

Hi,

You need to search for the tag "UserName" in that namespace:
C#
string NbV = xDocv.Descendants("UserName").First().Value;

C#
XNamespace ns = "http://schemas.monster.com/Monster";
string NbV = xDocv.Descendants(ns + "UserName").First().Value;


Optional information:

Furthermore, instead of this:
C#
string NbV = xDocv.Descendants(ns + "UserName").First().Value;

it might be better to use this:
C#
string NbV = (string)xDocv.Descendants(ns + "UserName").FirstOrDefault();

Why? If the tag would be missing, then you could avoid getting an error "Sequence contains no elements".
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900