How to add an attribute “type” for default data type of elements in XSLT transformation

好久不见. 提交于 2019-12-24 03:50:49

问题


For Example :

Input XML:

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

Data type for above request xml element has been defined in request Schema file. name is string, city is string and age is int data type.

Output of transformation should be like:

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

Please anyone give the solution for this transformation. Thanks in Advance


回答1:


You can use document() function to read your schema, e.g.:

Input XML:

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

Schema:

<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>

Produces desired Output XML:

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


来源:https://stackoverflow.com/questions/6695216/how-to-add-an-attribute-type-for-default-data-type-of-elements-in-xslt-transfo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!