XSLT怎么动态创建元素和属性 xsl:element, xsl:attribute

admin 百科 24
xsl:element和xsl:attribute支持动态生成元素名与属性名,name属性可用变量或XPath表达式(如{@role}、{concat('data-',@type)}),需确保名称合法且在xsl:element内定义。

XSLT怎么动态创建元素和属性 xsl:element, xsl:attribute-第1张图片-佛山资讯网

xsl:elementxsl:attribute 就能动态生成元素名和属性名,不写死标签,靠变量或表达式算出来。

用 xsl:element 动态创建元素

当元素名要根据数据变化时(比如字段类型不同生成不同标签),不能直接写 ``,得用 xsl:element

语法很简单:用 name 属性指定元素名,值可以是字符串、变量或 XPath 表达式。

  • 静态名字:<element name="person">...</element>
  • 用变量:<variable name="tag" select="'employee'"></variable><element name="{$tag}">...</element>
  • 根据内容判断:<element name="{@role}"><value-of select="name"></value-of></element> —— 如果 XML 中 role="admin",就生成 <admin>张三</admin>

用 xsl:attribute 动态添加属性

属性名(不只是属性值)也要动态?比如把字段名变成属性名,或者按条件加 classdata-* 。这时候 xsl:attributename 属性也支持表达式。

  • 固定属性名:<attribute name="id">123</attribute>
  • 动态属性名:<attribute name="{concat('data-', @type)}">yes</attribute> → 生成 data-userdata-system
  • 配合 xsl:if 条件加属性:<if test="@active='true"><attribute name="aria-current">page</attribute></if>

组合使用:动态元素 + 动态属性 + 内容

常见场景:把一个通用数据项转成带语义的 HTML 标签,比如 <field type="title" value="XSLT入门"></field><h2 class="section-title">XSLT入门</h2>

标签: html 处理器

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~

趣科技 机圈观察员 茄考网 茄录网 海印网 雷鹃网 鹃朝网 互联网观察员 评测官
趣科技 机圈观察员 茄考网 茄录网 海印网 雷鹃网 鹃朝网 互联网观察员 评测官