xslt - 如何使用 XSLT 转换和修改(!)嵌套标签?
问题描述
以这个 XML 为例...
<list>
<header>
something
</header>
<main>
<p>
(1) nothing <b>special</b> at all.
</p>
<p>
(1a) and <b>another</b> thing.
</p>
</main>
</list>
应该改成...
<list>
<header>
something
</header>
<aside>
<para nr="(1)">
nothing <u>special</u> at all.
</para>
<para nr="(1a)">
and <u>another</u> thing.
</para>
</aside>
</list>
这个 Stackoverflow 答案是我的出发点......
目前我没有真正的方法来解决这个问题。我不想引用我以前的失败...
解决方案
我不记得回答过那个引用的问题,但我给出的答案是采取的方法。你只需要实现一个数字规则......
- 转换
main
为aside
- 对于每个标签,根据第一个子文本元素中括号中的值向新创建的标签
p
添加属性nr
para
- 将元素
b
下的标签转换p
为u
第二个有点棘手,但可以使用这个模板来实现,它利用一些字符串操作来提取括号中的数字
<xsl:template match="p">
<para nr="{substring-before(substring-after(text()[1], '('), ')')}">
<xsl:apply-templates select="@*|node()"/>
</para>
</xsl:template>
(还要注意使用属性值模板来创建属性)
您还需要一个关联的模板来从第一个文本节点中删除数字
<xsl:template match="p/text()[1]">
<xsl:value-of select="substring-after(., ')')" />
</xsl:template>
不过转换b
为u
要容易得多(这是假设只有需要更改的b
元素)。p
<xsl:template match="p/b">
<u>
<xsl:apply-templates select="@*|node()"/>
</u>
</xsl:template>
将有一个类似的模板更改main
为aside
试试这个 XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<!-- This is the Identity Transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="main">
<aside>
<xsl:apply-templates select="@*|node()"/>
</aside>
</xsl:template>
<xsl:template match="p">
<para nr="{substring-before(substring-after(text()[1], '('), ')')}">
<xsl:apply-templates select="@*|node()"/>
</para>
</xsl:template>
<xsl:template match="p/text()[1]">
<xsl:value-of select="substring-after(., ')')" />
</xsl:template>
<xsl:template match="p/b">
<u>
<xsl:apply-templates select="@*|node()"/>
</u>
</xsl:template>
</xsl:stylesheet>
推荐阅读
- c# - 切换页面加载相同的左侧菜单
- python - Flask-CORS 不适用于 WSGI 中间件返回的响应
- typescript - ag-grid-react 正在尝试导入 WrapableInterface 但在 ag-grid-community 中不存在
- jquery - OAuth 服务提供商在无效的用户名/密码上返回 400/Bad Request
- bitbucket-pipelines - 缓存 bitbucket 管道映像
- azure - Azure Liquid 模板 - 如何从 Apim 策略中的嵌套 json 获取特定值
- c++ - 将 pegjs 转换为 C++
- r - 已解决 - Rcpp 在 MacOS Big Sur 上的 Vector.h 中返回错误
- python - Tkinter askdirectory()未显示在屏幕上
- php - MySQL全文搜索 - 多个搜索相同的字段