0

This is my XML:

   <start>
  <Move id = "1">
    <X1>234</X1>
    <Y1>234</Y1>
    <Z1>234</Z1>
  </Move>
  <Move id = "2">
    <X1>546</X1>
    <Y1>56</Y1>
    <Z1>345</Z1>
  </Move>
<start>

Now this is the code i am using to ceate it:

XDocument doc = new XDocument( new XElement( "start", 
 new XElement( "Move", new XAttribute("id", ""),
 new XElement( "X1", x1 ), 
  new XElement( "Y1", y1), 
 new XElement( "Z1", z1 ))));

Every time i'll start my program i will append node to this XML file and for that i need to retrieve last node which will give me node ID.

So in short ... "How do i access last node?"

I have tried but no success.

Could someone please help?

Thank you!

Tagyoureit
  • 359
  • 1
  • 5
  • 18

1 Answers1

0

Parse the xml:

var xdoc = XDocument.Parse(xml);

and then

int id = (int?)xdoc
    .Elements("start")
    .Elements("Move")
    .Attributes("id")
    .LastOrDefault() ?? 0;

id will be 0 if there are no Move elements, or with the last id otherwise.

Note that if you prefer,

int? id = (int?)xdoc
    .Elements("start")
    .Elements("Move")
    .Attributes("id")
    .LastOrDefault();

Now id will be null if there are no Move elements, or with the last id otherwise.

xanatos
  • 109,618
  • 12
  • 197
  • 280