【问题标题】:how to extract partial value from an element and assign as attribute to another element如何从元素中提取部分值并将其作为属性分配给另一个元素
【发布时间】:2012-03-16 06:45:48
【问题描述】:

我正在通过 XSLT 处理 XML 到 XML 的转换。

我想从元素中提取属性值并将其作为属性分配给新元素。

源 XML:

      <content>
        <component>
      <aaa>HI
           <strong>[a_b_c]</strong>
              : More Information Needed
            <strong>[d_e_f]</strong>XXX
      </aaa>
     </component>
     <content>

目标 XML:

    <ddd>hi<dv name='a_b_c'/>: More Information Needed <dv name='d_e_f'/> XXX

    </ddd>

任何人都可以建议如何通过 XSLT 做到这一点。

提前谢谢你。

【问题讨论】:

    标签: xml xslt xslt-grouping


    【解决方案1】:

    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="*"/>
    
      <xsl:template match="aaa">
        <ddd>
          <xsl:value-of select="substring-before(.,'[')"/>
          <dv name="{substring-before(substring-after(.,'['),']')}"/>
        </ddd>
      </xsl:template>
    
    </xsl:stylesheet>
    

    XSLT 2.0

    <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output indent="yes"/>
      <xsl:strip-space elements="*"/>
    
      <xsl:template match="aaa">
        <ddd>
          <xsl:value-of select="tokenize(.,'\[')[1]"/>
          <dv name="{tokenize(tokenize(.,'\[')[2],'\]')[1]}"/>
        </ddd>
      </xsl:template>
    
    </xsl:stylesheet>
    

    编辑

    <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="node()|@*">
        <xsl:copy>
          <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
      </xsl:template>
    
      <xsl:template match="aaa">
        <ddd>
          <xsl:apply-templates select="node()|@*"/>
        </ddd>
      </xsl:template>
    
      <xsl:template match="content|component">
        <xsl:apply-templates/>
      </xsl:template>
    
      <xsl:template match="strong">
        <dv name="{normalize-space(.)}"/>
      </xsl:template>
    
    </xsl:stylesheet>
    

    【讨论】:

    • 感谢您的建议..我已经编辑了问题,您可以修改答案,例如如何递归地进行。
    • @muzimil - 我不确定你所说的递归是什么意思。您的新输入/输出示例根本不需要字符串操作。您只需删除 contentcomponentstrong 元素并重命名 aaa 元素。
    • 不,我也删除了部分内容..像 [a_b_c] 等。递归我的意思是需要多次完成(如果需要删除更多内容)。
    • @muzimil - 该内容在strong 元素中。请尝试我更新中的样式表。
    • 对不起DevNull,我上传了错误的问题..现在我已经编辑了excat,请看一下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 2018-11-20
    • 1970-01-01
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多