1

I am having xml file with name as employeesInfo and in that the data is like

<?xml version="1.0" encoding="utf-8"?>
<EmployeeDetails>
  <data>
    <empCode>DIT-GINT-0001</empCode>
    <FirstName>Dinesh</FirstName>
    <LastName>Alla</LastName>
    <Address>Guntur</Address>
  </data>
  <EmployeeDetails>
    <empCode>DIT-GINT-0002</empCode>
    <FirstName>Upendra</FirstName>
    <LastName>Maddi</LastName>
    <Address>guntur</Address>       
  </EmployeeDetails>
  <EmployeeDetails>
    <empCode>DIT-GINT-0003</empCode>
    <FirstName>Chandrkanth</FirstName>
    <LastName>Beth</LastName>
    <Address>guntur</Address>       
  </EmployeeDetails>
</EmployeeDetails>

And My code to get attribute{"empCode"} value is

XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/employeesInfo.xml"));
XElement root = doc.Root;
string s = root.Elements("empCode").Last().ToString();

Requirement: I want to get empcode value of last parent element.

Example output of the above file: DIT-GINT-0003

3 Answers 3

2

In your code sample root is <EmployeeDetails>. Get its childnodes and select the last one, then get the <empCode> of this node. I am sorry that I am writing this as an answer, I don't have enough reputation.

XElement lastEmployeeDetails = root.LastNode;
Sign up to request clarification or add additional context in comments.

Comments

2

To get the last element and specific value in your case

XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/employeesInfo.xml"));
XElement root = doc.Root;
string s = root.Element("EmployeeDetails").Element("empCode").LastNode.ToString();

Comments

1

This can do the work -

XDocument doc = XDocument.Load(@"D:\Temp\asd.xml");
var s = doc.Descendants("empCode").Last().Value;

To check whether the node exists or not -

XDocument doc = XDocument.Load(@"D:\Temp\asd.xml");
var empCodes = doc.Descendants("empCode");
string result = string.Empty;

if(empCodes.Count() > 0)
{
     result = empCodes.Last().Value;
}

1 Comment

It works fine, I am having small doubt if suppose i am running the application for the first time then in the XML file i will not have "empcode" attribute, at that time how should i check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.