'Create parent-child elements based on attributes of child element

I have some XML data that looks like the following:

<view title="Logins">
    <parent title="User Activity" id="UserActivity"/>
</view>
<view title="Reports">
    <parent title="" id=""/>
</view>
<view title="Profile">
    <parent title="" id=""/>
</view>
<view title="Help Requests">
    <parent title="User Activity" id="UserActivity"/>
</view>

I would like to transform this XML so that each element with a parent title and id that isn't "" (blank/empty) will be together under the same parent element. If there is no parent, then I'd like for it to create an item like this:

<li class="nav-item w-100">
   <a href="#" class="nav-link">Reports</a>
</li>
<li class="nav-item w-100">
   <a href="#" class="nav-link">Profile</a>
</li>

If there is a parent id and title then I would like for it to create something like this where all child elements live under that one parent:

<div class="menu userActivity">
   <a data-toggle="collapse" href="#UserActivity" class="nav-link" role="button" aria-expanded="false" aria-controls="userActivityCollapse">
       <span class="mr-4">User Activity</span>
   </a>
   <div class="collapse" id="UserActivity">
       <ul class="nav">
          <li class="nav-item w-100">
             <a href="#" class="nav-link">Logins</a>
          </li>
          <li class="nav-item w-100">
             <a href="#" class="nav-link">Help Requests</a>
          </li>
       </ul>
   </div>
</div>

So the full output would look like this:

<div class="menu userActivity">
   <a data-toggle="collapse" href="#UserActivity" class="nav-link" role="button" aria-expanded="false" aria-controls="userActivityCollapse">
       <span class="mr-4">User Activity</span>
   </a>
   <div class="collapse" id="UserActivity">
       <ul class="nav">
          <li class="nav-item w-100">
             <a href="#" class="nav-link">Logins</a>
          </li>
          <li class="nav-item w-100">
             <a href="#" class="nav-link">Help Requests</a>
          </li>
       </ul>
   </div>
</div>
<li class="nav-item w-100">
   <a href="#" class="nav-link">Reports</a>
</li>
<li class="nav-item w-100">
   <a href="#" class="nav-link">Profile</a>
</li>
xml


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source