xml - (XSLT) 使用属性值对标签进行编号
问题描述
所以我得到了例如这个 xhtml 文件(https://xsltfiddle.liberty-development.net/bdxtqF):
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<p>first line</p>
<p>second line</p>
<p>third line</p>
<p>forth line</p>
<p>fifth line</p>
</body>
我想为 p 标签编号,但它们的值应被视为 id 属性。我知道您可以使用 xsl:number 但我只知道如何在节点内编号:
<?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"
xpath-default-namespace="http://www.w3.org/1999/xhtml"
exclude-result-prefixes="#all"
version="3.0">
<xsl:template match="body">
<test>
<xsl:apply-templates />
</test>
</xsl:template>
<xsl:template match="p">
<p><xsl:number/>. <xsl:apply-templates /></p>
</xsl:template>
</xsl:stylesheet>
但我想要的结果应该是这样的
<?xml version="1.0" encoding="UTF-8"?>
<test>
<p id="1">first line</p>
<p id="2">second line</p>
<p id="3">third line</p>
<p id="4">forth line</p>
<p id="5">fith line</p>
</test>
如何在标签内创建属性名称并开始对其中的值进行编号?提前致谢!
解决方案
您可以xsl:attribute
在此处使用来创建属性
<xsl:template match="p">
<p>
<xsl:attribute name="id">
<xsl:number />
</xsl:attribute>
<xsl:apply-templates />
</p>
</xsl:template>
或者,如果您添加strip-space
到样式表中,您可以使用position()
<xsl:strip-space elements="*" />
<xsl:template match="body">
<test>
<xsl:apply-templates />
</test>
</xsl:template>
<xsl:template match="p">
<p id="{position()}">
<xsl:apply-templates />
</p>
</xsl:template>
没有strip-space
将xsl:apply-templates
选择空白文本节点,这会影响位置。请注意,如果body
除此之外还有其他元素,p
则不会给您预期的结果。在这种情况下你可以这样做<xsl:apply-templates select="p" />
,但这会假设你想忽略其他元素。
推荐阅读
- c# - 用于检索已发送消息的 bulksms URI
- android - 如何在本地使用 WebRTC 进行视频通话流式传输时录制音频和视频?
- java - 覆盖索引无法优化mysql8.0中的limit查询
- java - 如何使用正则表达式匹配 Java 中的 HTML 标记内容
- excel - 引用名称中有空格的工作表
- jquery - replaceWith() P by Span 保留实际内容
- git - Git hook/post-receive 没有这样的文件或目录
- javascript - Javascript If Condition 未正确评估
- jquery - cxjs 从 jquery 插件构建 cxjs 小部件的最佳方法是什么?
- intellij-idea - 在 AppCode 中调试 Intellij Idea 插件