<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
  <xsl:output method="xml" encoding="utf-8"
        doctype-public="-//W3C//DTD Specification V2.10//EN"
        doctype-system="xmlspec.dtd" indent="no"/>
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="eg[@role='needs-numbering']">
<eg>
<xsl:for-each select="@*[not(name()='role')]">
<xsl:copy-of select="."/>
<xsl:attribute name="role"><xsl:text>numberAddedAutomatically</xsl:text></xsl:attribute>
</xsl:for-each>
        <xsl:variable name="egWithLb" as="item()*">
            <egWithLb>
                <lb/>
                <xsl:for-each select="text()|node()">
                    <xsl:choose>
                        <xsl:when test="self::text()">
                            <xsl:analyze-string select="." regex="&#xA;">
                                <xsl:matching-substring>
                                    <xsl:text>&#xA;</xsl:text>
                                    <lb/>
                                </xsl:matching-substring>
                                <xsl:non-matching-substring>
                                    <xsl:value-of select="."/>
                                </xsl:non-matching-substring>
                            </xsl:analyze-string>
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:copy-of select="."/>
                        </xsl:otherwise>
                    </xsl:choose>
                </xsl:for-each>
            </egWithLb>
        </xsl:variable>
        <xsl:apply-templates select="$egWithLb/node()" mode="addLineNumbers"/>
</eg>
    </xsl:template>
    <xsl:template match="lb" mode="addLineNumbers">
        <xsl:choose>
            <xsl:when
                test="not(contains(self::lb/following-sibling::text()[1],'xmlns'))">
                <xsl:text>(</xsl:text>
                <xsl:number format="01"
                    count="lb[not(contains(self::lb/following-sibling::text()[1],'xmlns'))]"/>
                <xsl:text>) </xsl:text>
            </xsl:when>
        </xsl:choose>
    </xsl:template>
    <xsl:template match="node()" mode="addLineNumbers">
        <xsl:copy-of select="."/>
    </xsl:template>
</xsl:stylesheet>
