Click here to Skip to main content
15,895,084 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi friends,
i am trying to create a list of object from XMl
problem is, in some cases particular path is not available. so my code throwing an exception stating "Object reference not set to an instance of object". How can i overcome this situation. if particular node is not available value should be empty.
please see the inline comments
C#
public static List<GetFaNumInBranch> SearchByUserID(string xmlstring, string UserId)
{
List<GetFaNumInBranch> FaDetails_Filter = new List<GetFaNumInBranch>();
XElement Xele;
Xele = RemoveAllNamespaces(XElement.Parse(xmlstring));
UserId = "PE9603";
var FaDetails_Filters = Xele.Descendants("FaNumInBranch")
	  .Where(item =>
	  {
		  string BranchUserId = (string)item.Element("BranchUserId") ?? "";
		  return BranchUserId != null && BranchUserId == UserId;
	  })
	 .Select(item => new GetFaNumInBranch
	 { 
		 FaType = (string)item.Element("AlternateFALIST").Element("AlternateFA").Element("FaType") ?? "",// in some case specific path will not available.so i am getting object reference  error
		 PrimaryFANumber = (string)item.Element("PrimaryFANumber") ?? "",
		 PrimaryBranch = (string)item.Element("PrimaryBranch") ?? "",
		 FirstName = (string)item.Element("FirstName") ?? "",
		 LastName = (string)item.Element("LastName") ?? "",
		 EmpNum = (string)item.Element("EmpNum") ?? "",
		 BranchUserId = (string)item.Element("BranchUserId") ?? ""
	 })
	 .ToList();               
return FaDetails_Filter;
}


XML
<FaNumInBranch>
  <BranchUserId>PB6442</BranchUserId>
  <EmpNum>B6442</EmpNum>
  <LastName>YAMADA </LastName>
  <FirstName>KAY </FirstName>
  <PrimaryBranch>0237</PrimaryBranch>
  <PrimaryFANumber>0663</PrimaryFANumber>
  <AlternateFALIST>
    <AlternateFA>
      <FaType>S</FaType>
      <BranchFAList>
        <BranchFA>
          <Branch>0237</Branch>
          <FA>0676</FA>
        </BranchFA>
Posted
Updated 22-Sep-15 20:47pm
v3

1 solution

In C# 6 it would be easy with the new ?. operator:
C#
FaType = (string)item.Element("AlternateFALIST")?.Element("AlternateFA")?.Element("FaType") ?? ""

Otherwise, I'd suggest using a separate (or anonymous or lambda) method to walk to the FAType:
C#
private static XElement SafePathWalker(XElement start, params string[] elementNames)
{
  // should check for start and elementNames != null
  XElement result = start;
  foreach (string name in elementNames)
  {
    result = result.Element(name);
    if (result == null)
      return null;
  }
  return result;  
}

Then:
C#
FaType = (string)SafePathWalker(item, "AlternateFALIST", "AlternateFA", "FAType") ?? ""

Edit: MTH
The SafePathWalker could be put into an extension methods class:
C#
public static ExtensionMethods
{
  public static XElement SafePathWalker(this XElement start, params string[] elementNames)
  {
    // should check for elementNames != null
    XElement result = start;
    // A regular for loop could work also (compare with above)
    for (int i = 0; result != null && i < elementNames.Length; ++i)
    {
      result = result.Element(elementNames[i]);
    }
    return result;  
  }
}

Then:
C#
FaType = (string)item.SafePathWalker("AlternateFALIST", "AlternateFA", "FAType") ?? ""
 
Share this answer
 
v2
Comments
jinesh sam 26-Sep-15 14:49pm    
in my code i am using FaType = (string)item.Element("AlternateFALIST")?.Element("AlternateFA")?.Element("FaType") ?? "" but its throwing error. Let me try with Extension Methods.
Thanks for your support :)
Matt T Heffron 28-Sep-15 12:46pm    
A compile time error?
Or run-time?
If compile-time, note that above I said this was only for C# 6 (I.e., VS 2015), not for earlier releases.
If run-time, then tell us what error (exception) is being thrown.
jinesh sam 29-Sep-15 14:32pm    
Run time error. I am using VS 2013
Error i am getting is: "Object reference not set to an instance of object"
Matt T Heffron 29-Sep-15 16:20pm    
the ?. operator is NOT PRESENT in VS2013 (C# 5).
The statement you've shown in the comment above shouldn't even compile in VS2013!

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


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