<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
	xmlns:xlink="http://www.w3.org/1999/xlink"
	xmlns:lib="http://my.library/syntax/"
	xmlns="http://my.library/syntax/">

<xsl:template match="/lib:library">
	<xsl:copy>
		<xsl:apply-templates select="lib:book"/>
	</xsl:copy>
</xsl:template>

<xsl:template match="lib:book">
	<xsl:copy>
		<xsl:apply-templates/>
		<xsl:variable name="id" select="concat('#', @id)"/>
		<xsl:apply-templates select="/lib:library/lib:links/lib:book[@xlink:href=$id]" mode="links1"/>
	</xsl:copy>
</xsl:template>

<xsl:template match="lib:book" mode="links1">
	<xsl:variable name="label" select="@xlink:label"/>
	<xsl:apply-templates select="../lib:arc[@xlink:from=$label]" mode="links2"/>
</xsl:template>

<xsl:template match="lib:arc" mode="links2">
	<xsl:variable name="label" select="@xlink:to"/>
	<xsl:apply-templates select="../*[@xlink:label=$label and @xlink:type='locator']" mode="links3"/>
</xsl:template>

<xsl:template match="*[@xlink:type='locator']" mode="links3">
	<xsl:copy-of select="id(substring-after(@xlink:href, '#'))" mode="links"/>
</xsl:template>

<xsl:template match="*|@*">
	<xsl:copy>
		<xsl:apply-templates/>
	</xsl:copy>
</xsl:template>

</xsl:stylesheet>