Split based on just tags

2019-09-15 01:12发布

问题:

I am looking for a simple split of an xml file just based on tags; say 3 tags always repeat and need split as depicted below:

Input

<?xml version="1.0" encoding="UTF-8"?>
<Test>
    <tag1>A</tag1>
    <tag2>B</tag2>
    <tag3>C</tag3>
    <tag1>1</tag1>
    <tag2>2</tag2>
    <tag3>3</tag3>
    <tag1>apple</tag1>
    <tag2>orange</tag2>
    <tag3>mango</tag3>
</Test>

Expected Output

<Root>
    <Test>
        <tag1>A</tag1>
        <tag2>B</tag2>
        <tag3>C</tag3>
    </Test>
    <Test>
        <tag1>1</tag1>
        <tag2>2</tag2>
        <tag3>3</tag3>
    </Test>
    <Test>
        <tag1>apple</tag1>
        <tag2>orange</tag2>
        <tag3>mango</tag3>
    </Test>
</Root>

Any help is appreciated

Thanks

回答1:

If the structure is regular, you could do simply:

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:template match="/Test">
    <Root>
        <xsl:for-each select="tag1">
            <Test>
                <xsl:copy-of select=". | following-sibling::tag2[1] | following-sibling::tag3[1] "/>
            </Test>
        </xsl:for-each>
    </Root>
</xsl:template>

</xsl:stylesheet>


标签: xslt split