我正在尝试返回 XML 表中的部分字符串。 我想保留“描述”字段中括号之间的内容,并将括号之外的内容移动到不同的字段:
源 XML:
<Log>
<Date>15-Nov-2014</Date>
<TC>14:38:47:13</TC>
<Description>Move this text (but keep this text here)</Description>
</Log>
期望的结果是:
<Log>
<Date>15-Nov-2014</Date>
<TC>14:38:47:13</TC>
<Description>but keep this text here</Description>
<MyOtherField>Move this text</MyOtherField>
</Log>
我尝试过在行中使用 substring-before "(" 和 'substring-after ")" 函数,输出几乎是正确的 - 但问题是,并非我的源 XML 工作表中的所有“描述”字段都有文本括号,所以那些被完全删除。
如有任何帮助,我们将不胜感激。
谢谢你
试试这个方法:
<xsl:template match="Description">
<xsl:copy>
<xsl:value-of select="substring-before(substring-after(., '('), ')')"/>
</xsl:copy>
<MyOtherField>
<xsl:value-of select="substring-before(concat(., '('), '(')"/>
</MyOtherField>
</xsl:template>
由于您使用的是 XSLT 2.0,因此您可以使用
xsl:analyze-string
来获取括号之间的文本...
XML 输入
<Log>
<Date>15-Nov-2014</Date>
<TC>14:38:47:13</TC>
<Description>Move this text (but keep this text here)</Description>
</Log>
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="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Description">
<xsl:copy>
<xsl:analyze-string select="." regex="\(([^)]+)\)">
<xsl:matching-substring>
<xsl:value-of select="regex-group(1)"/>
</xsl:matching-substring>
</xsl:analyze-string>
</xsl:copy>
<MyOtherField>
<xsl:value-of select="normalize-space(string-join((substring-before(concat(.,'('),'('),
substring-after(.,')')),' '))"/>
</MyOtherField>
</xsl:template>
</xsl:stylesheet>
XML 输出
<Log>
<Date>15-Nov-2014</Date>
<TC>14:38:47:13</TC>
<Description>but keep this text here</Description>
<MyOtherField>Move this text</MyOtherField>
</Log>
这里它已集成到您现有的代码中:http://xsltransform.net/pPzifq1/1
我能够使用以下模板实现这一目标:
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="Description[contains(text(), '(')]">
<Description>
<xsl:value-of select="substring-before(substring-after(., ' ('), ')')" />
</Description>
<MyOtherField>
<xsl:value-of select="substring-before(., ' (')" />
</MyOtherField>
</xsl:template>
</xsl:transform>
请注意,如果您有多个
(
或 )
,它可能无法按预期工作。这个想法是匹配任何包含 Description
的 (
标签,然后使用子字符串逻辑。
我有两根弦 String_1:“我每天步行,有时乘公共汽车或骑自行车” 更多长度范围为 20 t0 40, String_2:“没有火车” 更多长度范围为 10,
如果 String_1 的长度大于 30,那么我需要将 String_1 的子字符串拉到最近的空间(最近的空间长度可以小于或大于 30) String_1 的其余部分应连接到 String_2