PMOrion
PMOrion

Reputation: 169

XDocument Determine Last Child of Parent

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.

Upvotes: 3

Views: 1305

Answers (2)

Batuu
Batuu

Reputation: 595

You get the same result as in CBs answer without introducing all the booleans and use a linq-query:

    var query = from element in doc.Descendants()
                where element.ElementsBeforeSelf().Any() && !element.ElementsAfterSelf().Any() 
                select element;

    foreach (XElement element in query)
    {
      // Do something ...
    }

Upvotes: 0

C B
C B

Reputation: 647

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.

XDocument doc = XDocument.Parse("xmlPath");
foreach (XElement element in doc.Root.Descendants())
{
    bool hasChildren = element.HasElements;
    bool hasSiblings = element.ElementsBeforeSelf().Any() || element.ElementsAfterSelf().Any();
    bool isLastChild = hasSiblings && !element.ElementsAfterSelf().Any();
}

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.

Upvotes: 2

Related Questions