【问题标题】:How to add an attribute "type" for default data type of elements in XSLT transformation如何在 XSLT 转换中为元素的默认数据类型添加属性“类型”
【发布时间】:2011-07-14 14:51:43
【问题描述】:

例如:

输入 XML:

<employee>
     <name>Ragu</name>
     <city>Chennai</city>
     <age>25</age>
</employee>

上述请求 xml 元素的数据类型已在请求架构文件中定义。 name 是 string,city 是 string,age 是 int 数据类型。

转换的输出应该是这样的:

 <employee>
      <name type="string">Ragu</name>
      <city type="string">Chennai</city>
      <age type="int">25</age>
   </employee>

请任何人提供此转换的解决方案。提前致谢

【问题讨论】:

  • &lt;name&gt;Ragu&lt;/firstName&gt; XML 格式不正确

标签: xml xslt xpath xsd


【解决方案1】:

您可以使用document() 函数来读取您的架构,例如:

输入 XML:

<employee>
    <name>Ragu</name>
    <city>Chennai</city>
    <age>25</age>
</employee>

架构:

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="employee">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="name" type="xs:string" />
                <xs:element name="city" type="xs:string" />
                <xs:element name="age" type="xs:int" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs">
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="node()">

        <xsl:variable name="type" select="substring-after(document('schema.xsd')
                              //xs:element[@name = name(current())]/@type, ':')"/>
        <xsl:copy>
            <xsl:if test="$type">
                <xsl:attribute name="type">
                    <xsl:value-of select="$type"/>
                </xsl:attribute>
            </xsl:if>            
            <xsl:apply-templates/>
        </xsl:copy>

    </xsl:template>

</xsl:stylesheet>

生成所需的输出 XML:

<employee>
    <name type="string">Ragu</name>
    <city type="string">Chennai</city>
    <age type="int">25</age>
</employee>

【讨论】:

  • 上面给出的 XSLT 正在生成转换 Null。并且在请求中可能会出现任何有效的 xml。
  • @Sabapathy,您是否在 XSLT 中指定了到 schema.xsd 的正确路径?
  • @Sabapathy,您的 XSLT 处理器(顺便说一句,哪个?)输出具体是什么?
  • @Sabapathy,我不知道所有的 XSLT 引擎,但在 MSXML 中 document() 函数默认是不允许的。所以 mb 你需要启用这个选项。并生成消息/错误/异常的全文。
猜你喜欢
  • 1970-01-01
  • 2017-08-04
  • 1970-01-01
  • 1970-01-01
  • 2020-04-09
  • 2010-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多