Walking an XML document with XDocument using descendants how would I determine I am at the last child of the parent?
XDocument xmlDoc = XDocument.Parse(xml)
foreach (var element in xmlDoc.Descendants())
{
//Need to determine the last child of the parent and do something here.
}
Example of XML and what is expected to be returned. I need to dynamically walk the document and not specify the XPath or Xquery since these will be used generically for various XML documents without getting into a lot of details of the why… Just looking to see if I can do this with XDocument or if there is a better approach still not specifying the tag names in a XPath or XQuery unless it can be done dynamically without knowing how many levels deep the document may be.,
<?xml version="1.0"?>
<Root>
<Customer>
<CustID>1</CustID>
<Name>Smith, Joe</Name>
<CustomerTransDetail>
<CustID>1</CustID>
<CustTransID>1</CustTransID>
<Note>NA</Note>
</CustomerTransDetail>
<CustomerTransDetail>
<CustID>1</CustID>
<CustTransID>2</CustTransID>
<Note>N/A</Note>
</CustomerTransDetail>
</Customer>
<Customer>
<CustID>2</CustID>
<Name>Smith, Jane</Name>
<CustomerTransDetail>
<CustID>2</CustID>
<CustTransID>1</CustTransID>
<Note>N/A</Note>
</CustomerTransDetail>
<CustomerTransDetail>
<CustID>2</CustID>
<CustTransID>2</CustTransID>
<Note>N/A</Note>
</CustomerTransDetail>
</Customer>
</Root>
I need to know when I hit the last child of the parent so I can do something. So every time I hit Name node or Note node for example I can do something.
I’m still a little unclear as to what you’re attempting to do, but hopefully this can point you in the right direction.
You’re using XDocument, so I’m assuming you’re in at least .NET 3.5. You can most likely use the Linq to XML extension methods to achieve what you want.
Depending on what you need to do as you traverse the nodes, you may want to consider recursion as you walk the tree. That way you can determine as you go whether the element has siblings, is the last sibling, etc.