简体   繁体   中英

XQuery | How to transform all attributes into elements

I need to prepare a single XQuery file, which for any input XML file will transform all attributes into elements. I have it done in XSLT down below. tranformation.xsl :

<xsl:template match="*" name="xsl:initial-template">
    <xsl:element name="{name()}">
        <xsl:for-each select="@*">
            <xsl:element name="{name()}">
                <xsl:value-of select="."/>
            </xsl:element>
        </xsl:for-each>

        <xsl:apply-templates select="child::node()"/>

    </xsl:element>
</xsl:template>

In XQuery 3.1 you can use

declare function local:apply($nodes as node()*) as node()* {
    $nodes ! (
        typeswitch(.) 
            case document-node() 
              return local:apply(node())
            case element() 
              return element {node-name()} {
                                              @* ! element{node-name()} { data() }, 
                                              local:apply(node()) 
                                           }
            default return .
    )
};

local:apply(/)

Online example at https://xqueryfiddle.liberty-development.net/bFukv8c/3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM