You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用XSLT读取XSD选项及XML默认值生成指定HTML表单?

可用的XSLT转换规则

以下XSLT 1.0兼容代码可以实现你需要的转换效果,使用前请将代码中的your-schema-file.xsd替换为你实际的XSD文件路径:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xsl:output method="html" indent="yes" omit-xml-declaration="yes"/>

  <!-- 加载外部XSD schema文件 -->
  <xsl:variable name="schema" select="document('your-schema-file.xsd')/xs:schema"/>

  <!-- 匹配XML根节点book -->
  <xsl:template match="book">
    <xsl:apply-templates select="*"/>
  </xsl:template>

  <!-- 匹配book下的所有子章节节点 -->
  <xsl:template match="book/*">
    <xsl:variable name="current-element-name" select="local-name()"/>
    <xsl:variable name="current-value" select="normalize-space(text())"/>
    <!-- 查找XSD中对应元素的定义 -->
    <xsl:variable name="schema-element" select="$schema/xs:element[@name = $current-element-name]"/>

    <!-- 输出章节标题 -->
    <h1><xsl:value-of select="$current-element-name"/></h1>

    <xsl:choose>
      <!-- 节点类型带枚举值的情况,生成下拉选择框 -->
      <xsl:when test="$schema-element/xs:simpleType/xs:restriction/xs:enumeration">
        <select>
          <xsl:for-each select="$schema-element/xs:simpleType/xs:restriction/xs:enumeration">
            <xsl:variable name="enum-val" select="@value"/>
            <option>
              <xsl:if test="$enum-val = $current-value">
                <xsl:attribute name="selected">selected</xsl:attribute>
              </xsl:if>
              <xsl:value-of select="$enum-val"/>
            </option>
          </xsl:for-each>
        </select>
      </xsl:when>
      <!-- 节点类型无枚举值的情况,生成文本输入框 -->
      <xsl:otherwise>
        <input type="text" value="{$current-value}"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>

补充说明

  • 转换逻辑只会处理你XML中实际存在的节点,XSD中定义但XML里没有的节点不会输出
  • 你给出的期望输出中chapter3部分末尾多了一个冗余的</select>标签属于笔误,上述代码不会生成该无效标签

内容的提问来源于stack exchange,提问作者leonard vertighel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 05:30:03