使用 XSLT 1.0 组合 XML [英] Combining XML using XSLT 1.0

查看:26
本文介绍了使用 XSLT 1.0 组合 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要映射以下内容,但很难,因为它有不同的名称:

I need to map the following but its difficult because it has different names:

<main>
    <order>
        <ID>123</ID>
        <Name>ABC</Name>
    </order>
    <order>
        <ID>4556</ID>
        <Name>AAA</Name>
        <ParentID>123</ParentID>
    </order>
</main>

结果应该是:

<main>
    <order>
        <ID>123</ID>
        <Name>ABC</Name>
        <order>
            <ID>4556</ID>
            <Name>AAA</Name>
            <ParentID>123</ParentID>
        </order>
    </order>
</main>

推荐答案

就像@michael.hor257k 所说的,从概念上讲,这个问题与您之前的问题相同.我想你只是没有理解这个概念.希望我的示例中的注释会有所帮助.

Like @michael.hor257k said, conceptually this question is the same as your previous question. I think you're just not understanding the concept. Hopefully the comments in my example will help.

如果我正确理解了这个问题,您希望基于 ParentIDorder 元素嵌套在其父"order 元素中.由于我们基于 ParentID,这就是我们将用于我们的密钥...

If I understand the question correctly, you want to nest order elements inside of their "parent" order element based on ParentID. Since we're basing it on the ParentID, that's what we'll use for our key...

XML 输入

<main>
    <order>
        <ID>123</ID>
        <Name>ABC</Name>
    </order>

    <order>
        <ID>4556</ID>
        <Name>AAA</Name>
        <ParentID>123</ParentID>
    </order>
</main>

XSLT 1.0

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

  <!--Create a key containing order elements that contain a non-empty ParentID.-->
  <xsl:key name="orderByParentId" match="order[string(ParentID)]" use="ParentID"/>

  <!--Identity transform (https://www.w3.org/TR/xslt#copying)-->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="/main">
    <xsl:copy>
      <!--To get the high level order elements, only apply-templates when order
      does not contain a non-empty ParentID child.-->
      <xsl:apply-templates 
        select="@*|order[not(string(ParentID))]"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="order">
    <xsl:copy>
      <!--Don't apply-templates to ParentID; we don't want to keep those.
      Do apply-templates to the key 'orderByParentId' when the key matches
      the current order's ID child.-->
      <xsl:apply-templates 
        select="@*|*[not(self::ParentID)]|key('orderByParentId',ID)"/>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

输出

<main>
   <order>
      <ID>123</ID>
      <Name>ABC</Name>
      <order>
         <ID>4556</ID>
         <Name>AAA</Name>
      </order>
   </order>
</main>

这篇关于使用 XSLT 1.0 组合 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆