<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns="http://xml.insee.intra/schema/annuaire/" xmlns:q="http://xml.insee.intra/schema/qbe/">
    <xsl:strip-space elements="*"/>
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="rdf:RDF">
        <xsl:apply-templates select="." mode="root"/>
    </xsl:template>
    <xsl:template match="rdf:RDF" mode="root">
        <xsl:copy>
            <xsl:apply-templates mode="resource"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="text()" mode="resource"/>
    <xsl:template match="*" mode="resource">
        <xsl:copy>
            <xsl:copy-of select="@rdf:ID"/>
            <xsl:if test="not(@rdf:ID)">
                <xsl:attribute name="rdf:ID">
                    <xsl:value-of select="generate-id()"/>
                </xsl:attribute>
            </xsl:if>
            <xsl:apply-templates mode="property-ref"/>
        </xsl:copy>
        <xsl:apply-templates select="*" mode="property-def"/>
    </xsl:template>
    <xsl:template match="*" mode="property-ref">
        <xsl:for-each select="*">
            <xsl:element name="{name(parent::*)}">
                <xsl:attribute name="rdf:resource">
                    <xsl:text>#</xsl:text>
                    <xsl:value-of select="generate-id(.)"/>
                </xsl:attribute>
            </xsl:element>
        </xsl:for-each>
    </xsl:template>
    <xsl:template match="*[not(*|@rdf:resource)]" mode="property-ref">
        <xsl:copy-of select="."/>
    </xsl:template>
    <xsl:template match="*[@rdf:parseType='Resource']" mode="property-ref" priority="1">
        <xsl:copy>
            <xsl:attribute name="rdf:resource">
                <xsl:text>#</xsl:text>
                <xsl:value-of select="generate-id(.)"/>
            </xsl:attribute>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="*[@rdf:resource]" mode="property-ref">
        <xsl:copy-of select="."/>
    </xsl:template>
    <xsl:template match="*[@rdf:parseType='Resource']" mode="property-def" priority="1">
        <rdf:Description rdf:ID="{generate-id()}">
            <xsl:apply-templates mode="property-ref"/>
        </rdf:Description>
        <xsl:apply-templates mode="property-def"/>
    </xsl:template>
    <xsl:template match="*" mode="property-def">
        <xsl:apply-templates select="*" mode="resource"/>
    </xsl:template>
    <xsl:template match="*[@rdf:resource]" mode="property-def"/>
</xsl:stylesheet>
