首页 > 解决方案 > 如何使用 XML 中的子字符串在多个节点中使用 XLS 修改元素的属性值

问题描述

我正在尝试更改此 XML 示例中所有节点中的类别“名称”值

<?xml version="1.0" encoding="utf-8"?>
<offer xmlns:iof="********" xmlns:iaiext="******" file_format="IOF" generated="***" expires="***" version="3.0" extensions="yes">
  <products currency="EUR" iof_translation_generated="no" language="eng">
    <product id="170" currency="EUR" code_on_card="******" producer_code_standard="GTIN13" type="regular" vat="23.0" site="1">
      <producer id="1404978613" name="Test"/>
      <category id="1214554589" name="Cell phone screwdrivers"/>
      <category_idosell id="2898" path="Hardware &gt; Tools"/>
      <unit id="0" name="pc."/>
      <warranty id="2" type="seller" period="12" name="Cell phone accessories"/>
      <price gross="1.1" net="0.9"/>
    </product>
    <product id="411" currency="EUR" code_on_card="******" producer_code_standard="OTHER" type="regular" vat="23.0" site="1">
      <producer id="1404978613" name="Test"/>
      <category id="1214554594" name="Service Tools"/>
      <category_idosell id="2898" path="Hardware &gt; Tools"/>
      <unit id="0" name="pc."/>
      <warranty id="1" type="seller" period="6" name="Cell phone spare parts"/>
      <price gross="10.84" net="8.82"/>
    </product>
</products>
</offer>

使用这个 XSL 片段:

<?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="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>
<xsl:template match="category/@name">
   
        <xsl:element name="category">
            <xsl:attribute name="name">
                <xsl:value-of select="substring-before(//category_idosell[1]/@path, ' &gt; ')"/>
                <xsl:value-of select="'///'"/>
                <xsl:value-of select="substring-after(//category_idosell[1]/@path, ' &gt; ')"/>
                <xsl:value-of select="'///'"/>
                <xsl:value-of select="//category[1]/@name"/>
            </xsl:attribute>
        </xsl:element>
    </xsl:template>
    
</xsl:stylesheet>

当我在单个节点中使用它时它可以工作,但是当我有更多节点(产品)时它会给我这个错误:

A sequence of more than one item is not allowed as the first argument of fn:substring-before() ("Hardware > Tools", "Hardware > Tools")

有人可以帮我解决我想念的事情以及如何让它发挥作用吗?先感谢您

标签: xmlxsltcode-snippets

解决方案


你还没有说你想要什么输出,所以很难纠正你的代码。

如果要从文档中的第一个产品中获取值,请使用

(//category_idosell)[1]

如果要从当前产品中获取价值,请使用

../category_idosell

推荐阅读