Search code examples
c#xmlxml-parsingxelement

C# getting last element's attribute values from XML


I have below XML.

  <Bd>
  <GEvt ZipCode="xyz" EvtDtm="2020-03-12T02:26:35+01:00"></GEvt>
  <GEvt ZipCode="abc" EvtDtm="2020-03-12T02:32:35+01:00"></GEvt>
  <GEvt ZipCode="def" EvtDtm="2020-03-12T02:34:35+01:00"></GEvt>
  </Bd>

I dont need first two. I only need the last one;

<GEvt ZipCode="def" EvtDtm="2020-03-12T02:34:35+01:00"></GEvt>

Here is my code;

  var lineItemDetails = xdoc.Root?.Descendants("Bd");

  foreach (var lineItemDetail in lineItemDetails?.Nodes().OfType<XElement>())
    {
    var ZipCode = lineItemDetail?.Attribute("ZipCode")?.Value;
    var EvtDtm = lineItemDetail?.Attribute("EvtDtm")?.Value;
    Console.WriteLine(ZipCode);
    Console.WriteLine(EvtDtm);
    }

It's working fine but it's returning all 3 values from XML. However i only need the last one. I tried to use Last() but it didnt work. Using Last() bringing me last character. I need only this;

<GEvt ZipCode="def" EvtDtm="2020-03-12T02:34:35+01:00"></GEvt>

How to achieve it? What am i missing?


Solution

  • Check it out. It finds last <GEvt.../> XML element based on its position.

    c#

    void Main()
    {
        const string GEVT = "GEvt";
        const string ZIPCODE = "ZipCode";
        const string EVTDTM = "EvtDtm";
    
        XElement xml = XElement.Parse(@"<Bd>
            <GEvt ZipCode='xyz' EvtDtm='2020-03-12T02:26:35+01:00'></GEvt>
            <GEvt ZipCode='abc' EvtDtm='2020-03-12T02:32:35+01:00'></GEvt>
            <GEvt ZipCode='def' EvtDtm='2020-03-12T02:34:35+01:00'></GEvt>
            </Bd>");
    
        // get desired XML element
        XElement lastElement = xml.Elements(GEVT).Last();
    
        // get attributes values
        string Zipcode = lastElement.Attributes(ZIPCODE).FirstOrDefault().Value;
        string EvtDtm = lastElement.Attributes(EVTDTM).FirstOrDefault().Value;
    }