【问题标题】:How to send multiple XML levels to output with XSLT如何使用 XSLT 将多个 XML 级别发送到输出
【发布时间】:2023-03-29 16:56:01
【问题描述】:

我正在使用 XSL 文件来转换一些嵌套的 XML。我想将两层嵌套层次结构展平为两个对象列表,同时通过添加键来保留关系。

我已经设置了 XSL,将每个父级的密钥分配给它的子级,然后只输出子级注释。

源 XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <parent>
        <parent-id>1</parent-id>
        <child>
            <child-id>child_a</child-id>
        </child>
    </parent>
    <parent>
        <parent-id>2</parent-id>
        <child>
            <child-id>child_b</child-id>
        </child>
    </parent>
</root>

XSL:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:strip-space elements="*"/>


<xsl:template match="text()" /> 

<xsl:template match="root">
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>

<xsl:template match="root/*">
    <xsl:apply-templates/>
</xsl:template>


<xsl:template match="child">
    <xsl:copy>
        <xsl:copy-of select="*"/>
        <foreignkey><xsl:value-of select="ancestor::parent/parent-id"/></foreignkey>
    </xsl:copy>
</xsl:template>

<xsl:template match="parent">
    <xsl:copy>
        <xsl:copy-of select="*"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

这看起来正是我想要的,但我还想像这样添加父母(现在没有嵌套的孩子):

<parent>
    <parent-id>1</parent-id>
</parent>

<parent>
    <parent-id>2</parent-id>
</parent>

我需要在 XSL 文件中添加什么才能让父母在孩子之前或之后输出?我可以输出一个或另一个,但不能同时输出。

【问题讨论】:

    标签: xml xslt


    【解决方案1】:

    您可以在root 模板内使用两次apply-templates

    <xsl:template match="root">
        <xsl:copy>
            <xsl:apply-templates select="parent"/>
            <xsl:apply-templates select="parent/child"/>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="child">
        <xsl:copy>
            <xsl:copy-of select="*"/>
            <foreignkey><xsl:value-of select="ancestor::parent/parent-id"/></foreignkey>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="parent">
        <xsl:copy>
            <xsl:copy-of select="parent-id"/>
        </xsl:copy>
    </xsl:template>
    

    然后你得到例如

    <root>
       <parent>
          <parent-id>1</parent-id>
       </parent>
       <parent>
          <parent-id>2</parent-id>
       </parent>
       <child>
          <child-id>child_a</child-id>
          <foreignkey>1</foreignkey>
       </child>
       <child>
          <child-id>child_b</child-id>
          <foreignkey>2</foreignkey>
       </child>
    </root>
    

    【讨论】:

    • 马丁,谢谢!我试过拍&lt;xsl:apply-templates.../&gt;,除了那里。
    猜你喜欢
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多