You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

XSLT转换XML:属性转标签及图片、规格标签生成求助

解决带属性XML到标签式XML的XSLT转换问题

需要将带有属性的XML转换为标准标签式XML(如<id>1</id>)。现有XSLT代码可正常将Product的属性转为标签,但存在两个问题:

  • 图片处理部分仅生成空的<image1/>标签,无法正确提取图片URL并生成带编号的图片标签
  • 不知道如何将TechnicalSpecification中的属性及对应值转换为标签

原始XML

<Product id="1" name="Sample Product" price="99.99">
  <Images>
    <Image url="https://example.com/img1.jpg"/>
    <Image url="https://example.com/img2.jpg"/>
  </Images>
  <TechnicalSpecification weight="1kg" dimension="20x30x10cm" material="Plastic"/>
</Product>

期望输出

<Product>
  <id>1</id>
  <name>Sample Product</name>
  <price>99.99</price>
  <image1>https://example.com/img1.jpg</image1>
  <image2>https://example.com/img2.jpg</image2>
  <TechnicalSpecification>
    <weight>1kg</weight>
    <dimension>20x30x10cm</dimension>
    <material>Plastic</material>
  </TechnicalSpecification>
</Product>

现有XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <!-- 处理Product属性 -->
  <xsl:template match="Product">
    <Product>
      <xsl:for-each select="@*">
        <xsl:element name="{name()}">
          <xsl:value-of select="."/>
        </xsl:element>
      </xsl:for-each>
      <!-- 图片处理(当前有问题) -->
      <image1/>
      <!-- TechnicalSpecification处理(未实现) -->
    </Product>
  </xsl:template>
</xsl:stylesheet>

当前输出

<Product>
  <id>1</id>
  <name>Sample Product</name>
  <price>99.99</price>
  <image1/>
</Product>

修正后的XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="Product">
    <Product>
      <!-- 处理Product的所有属性 -->
      <xsl:for-each select="@*">
        <xsl:element name="{name()}">
          <xsl:value-of select="."/>
        </xsl:element>
      </xsl:for-each>

      <!-- 处理图片,生成带编号的标签并提取URL -->
      <xsl:for-each select="Images/Image">
        <xsl:element name="image{position()}">
          <xsl:value-of select="@url"/>
        </xsl:element>
      </xsl:for-each>

      <!-- 处理TechnicalSpecification的属性 -->
      <xsl:if test="TechnicalSpecification">
        <TechnicalSpecification>
          <xsl:for-each select="TechnicalSpecification/@*">
            <xsl:element name="{name()}">
              <xsl:value-of select="."/>
            </xsl:element>
          </xsl:for-each>
        </TechnicalSpecification>
      </xsl:if>
    </Product>
  </xsl:template>
</xsl:stylesheet>

关键修改说明

  • 图片处理:用xsl:for-each遍历Images/Image节点,通过position()动态生成图片编号(image1、image2...),并提取@url属性值作为标签内容。
  • TechnicalSpecification处理:先判断节点是否存在,再遍历其所有属性,将属性名转为标签名,属性值作为标签内容,包裹在<TechnicalSpecification>标签内。

内容的提问来源于stack exchange,提问作者user20508390

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 16:46:30