首页 > 解决方案 > XSL 循环遍历 XML 元素的属性,然后用连接的属性替换第一个元素

问题描述

例如,这是我的文件

<offer>
<products>
  <product>
    <images>
        <large>
          <image priority="1" url="data/gfx/pictures/large/9/7/70679_1.jpg" hash="74c757e1dfc9277d6f6ba49c0ca*****" changed="2021-06-18 15:57:02" width="1000" height="1000"/>
          <image priority="2" url="data/gfx/pictures/large/9/7/70679_2.jpg" hash="74c757e1dfc9277d6f6ba49c0ca*****" changed="2021-06-18 15:57:02" width="1000" height="1000"/>
          <image priority="3" url="data/gfx/pictures/large/9/7/70679_3.jpg" hash="74c757e1dfc9277d6f6ba49c0ca*****" changed="2021-06-18 15:57:02" width="1000" height="1000"/>
        </large>
    </images>
  </product>
</products>
</offer>

我想将所有图像 URL 属性与 /// 组合(可以是任意数量的图像元素)在下面的示例中,它具有 3 个图像元素,例如,我需要的结果是:

<offer>
<products>
  <product>
    <images>
        <large>

          <image priority="1" url="data/gfx/pictures/large/9/7/70679_1.jpg///data/gfx/pictures/large/9/7/70679_2.jpg///data/gfx/pictures/large/9/7/70679_3.jpg" hash="74c757e1dfc9277d6f6ba49c0ca*****" changed="2021-06-18 15:57:02" width="1000" height="1000"/>
          
        </large>
    </images>
  </product>
</products>
</offer>

我试过这个但失败了

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

<xsl:template match="/offer/products/product/images/large/image">
        <xsl:for-each select="image[*]/@url">
            <xsl:value-of select="concat(../../../images/large/image/@path,'///')"/>                    
        </xsl:for-each>
        
 </xsl:template>
 </xsl:stylesheet>

这怎么可能?预先感谢您的帮助

标签: xmlxsltforeachconcatenation

解决方案


请尝试以下 XSLT。

Saxon PE 9.9.1.7 与 XSLT 3.0 兼容

string-join()功能可以发挥所有作用。

XSLT

<?xml version='1.0'?>
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" expand-text="yes">
   <xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="yes"/>
   <xsl:strip-space elements="*"/>

   <xsl:mode on-no-match="shallow-copy"/>

   <xsl:template match="large">
      <xsl:copy>
         <image priority="1"
                           url="{string-join((image/@url), '///')}"
                           hash="{image[1]/@hash}"
                           changed="{image[1]/@changed}" width="{image[1]/@width}"
                           height="{image[1]/@height}"/>
      </xsl:copy>
   </xsl:template>
</xsl:stylesheet>

推荐阅读