'Add <ol>/<ul> to all <li> tags that doesn't have <ol>/<ul> as it's parent XSLT

I have this kind of xml where some <li> tags doesn't have <ol>/<ul> as it's parent. Need to add as it's parent.

Example:

<root>
    <p>some text</p>
    <ol>
      <li>
         <a href="http://cowherd.com" rel="nofollow">http://cowherd.com</a>
      </li>
    </ol>
    <li>some text</li>
    <li>some text</li>
    <p>some more text</p>
    <li>some text in li.</li>
    <p>some more text</p>
    <li>some text in li.</li>
</root>   

Desired Output: I want to add a parent <ol>or<ul> tag to those <li>tags which don't have it's parent as <ol>/<ul>. And also if there are continuesly more than one <li> tag then all the <li> tags should come under same <ul>/<ol>just like below. Thanks in advance.

<root>
    <p>some text</p>
    <ol>
      <li>
         <a href="http://cowherd.com" rel="nofollow">http://cowherd.com</a>
      </li>
    </ol>
    <ol>
      <li>some text</li>
      <li>some text</li>
    </ol>
    <p>some more text</p>
    <ol> 
      <li>some text in li.</li>
    </ol>
    <p>some more text</p>
    <ol>
      <li>some text in li.</li>
    </ol>
</root>


Solution 1:[1]

To give you a start:

if those li without a parent ol can occur everywhere use this match:

  <xsl:template match="*[li[not(parent::lo)]]">

And like @Martin Honnen in his comment suggest make use of

<xsl:for-each-group select="*" group-adjacent=". instance of element(li)">

In that group-loop you can then make use of current-grouping-key() and current-group()

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Siebe Jongebloed