【问题标题】:Split element within xslt file在 xslt 文件中拆分元素
【发布时间】:2022-10-20 10:24:44
【问题描述】:

我有以下输入

UK/006/10
US/004/12

并希望得到以下输出。

Country: UK
Code:006
Line: 10

Country: US
Code:004
Line:12

我尝试使用以下功能,但我需要一些简单的东西,例如拆分功能。有人可以帮忙吗?

<xsl:value-of select="substring-before(substring-after($User_def_type_4, '/'), '/')" />

【问题讨论】:

  • XSLT 2 还是 3?使用tokenize 和/或分析字符串。
  • 即使在 XSLT 1.0 中,您的处理器也可能支持 EXSLT str:split() 或 str:tokenize() 扩展函数。

标签: xslt invisible-xml


【解决方案1】:

使用Invisible XML,您可以为您的文本数据定义一个语法以将其映射到 XML,然后可以在 XSLT 中使用像撒克逊 Java 的 CoffeeSacks 库这样的扩展函数库来解析和后处理文本,以便使用例如XML 输入是

<data>UK/006/10
US/004/12</data>

XSLT 是

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  version="3.0"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:cs="http://nineml.com/ns/coffeesacks"
  exclude-result-prefixes="#all"
  expand-text="yes">
  
  <xsl:template match="data">
    <xsl:apply-templates select="cs:parse-string(cs:grammar-string($grammar), .)/node()"/>
  </xsl:template>
      
  <xsl:output method="xml" indent="yes"/>

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

  <xsl:template match="/" name="xsl:initial-template">
    <xsl:next-match/>
    <xsl:comment xmlns:saxon="http://saxon.sf.net/">Run with {system-property('xsl:product-name')} {system-property('xsl:product-version')} {system-property('Q{http://saxon.sf.net/}platform')}</xsl:comment>
  </xsl:template>

  <xsl:param name="grammar" as="xs:string" expand-text="no">Countries = Country*.
Country = Name, -'/', Code, -'/', Line, #A?.
Name = ['A'-'Z'],['A'-'Z'].
Code = ['0'-'9'],['0'-'9'],['0'-'9'].
Line = ['0'-'9'],['0'-'9'].</xsl:param>

</xsl:stylesheet>

你得到例如

<?xml version="1.0" encoding="UTF-8"?>
<Countries>
   <Country>
      <Name>UK</Name>
      <Code>006</Code>
      <Line>10</Line>
   </Country>
   <Country>
      <Name>US</Name>
      <Code>004</Code>
      <Line>12</Line>
   </Country>
</Countries>
<!--Run with SAXON HE 11.3 --> 

Online sample using Saxon HE 11 Java and the named CoffeeSacks library

【讨论】:

  • 感谢您的帮助,我也找到了另一种方法 <xsl:variable name="name_code_line" select="tokenize(data,'/')" /> <xsl:value-of select="$name_code_line[0]" />
猜你喜欢
  • 2021-11-24
  • 2014-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多