繁体   English   中英

XSLT复制父节点中的子节点

[英]XSLT copy child nodes in parent node

我需要将子元素复制到父元素中。

输入

<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>

期望的输出

<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>

我尝试了什么(输出保持与输入相同):

<?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>

我肯定会在这里错过一些非常简单的事情。 子元素与父元素具有相同的名称应该没问题吗?

您确实需要第二个模板仅匹配子row ,而不匹配父row 然后,您可以选择其子级,但不能复制自身

试试这个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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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