combining xml, xpath or xquery

2019-03-04 15:51发布

问题:

<main>
    <parent>
        <parentId>parentId1</parentId>
        <aParentField>aParentValue
        </aParentField>
    </parent>
    <child>
        <parentId>parentId1</parentId>
        <aChildField>aChildValue
        </aChildField>
    </child>
</main>

I am new to XML and was trying to combine A and B using the ID as a parameter to combine, so the result should be like:

<main>
    <parent>
        <parentId>parentId1</parentId>
        <aParentField>aParentValue
        </aParentField>
        <child>
            <aChildField>aChildValue
        </aChildField>
        </child>
    </parent>
</main>

What can be used and how ?

回答1:

The example is a little ambiguous. Assuming your input can have multiple parent nodes, each linked to multiple child nodes, I would suggest you use a key to resolve the cross-references:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:key name="child" match="child" use="parentId" />

<xsl:template match="/main">
    <xsl:copy>
        <xsl:apply-templates select="parent"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="parent">
    <xsl:copy>
        <xsl:copy-of select="*"/>
        <xsl:apply-templates select="key('child', parentId)"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="child">
    <xsl:copy>
        <xsl:copy-of select="*[not(self::parentId)]"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>