How to add an attribute “type” for default data ty

2019-07-16 05:05发布

问题:

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>


标签: xml xslt xpath xsd