简体   繁体   中英

XSLT copy child nodes in parent node

I need to copy child elements into the parent element.

input

<csv>
<row>
    <stuff>a</stuff>
    <more>1</more>
    <evenmore>123</evenmore>
    <row>
        <other>1345</other>
        <stuff>dga</stuff>
    </row>
</row>
<row>
    <stuff>b</stuff>
    <more>2</more>
    <evenmore>456</evenmore>
    <row>
        <other>4576</other>
        <stuff>jzj</stuff>
    </row>
</row>
</csv>

desired output

<csv>
<row>
    <stuff>a</stuff>
    <more>1</more>
    <evenmore>123</evenmore>
    <other>1345</other>
    <stuff>dga</stuff>
</row>
<row>
    <stuff>b</stuff>
    <more>2</more>
    <evenmore>456</evenmore>
    <other>4576</other>
    <stuff>jzj</stuff>
</row>
</csv>

What I tried (the output stays the same like the input):

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

<xsl:strip-space elements="*"/>
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="row">
    <xsl:copy>
        <xsl:apply-templates/>
        <xsl:apply-templates select="child::row/row/other | child::row/row/stuff"/>
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>

I am sure to miss something very simple here. It should not be a problem, that the child element has the same name as the parent element?

You really need your second template to only match the child row , and not the parent one. Then you can select its children, but just not copy it itself

Try this XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:strip-space elements="*"/>
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="row/row">
    <xsl:apply-templates/>
</xsl:template>
</xsl:stylesheet>

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