This may not be the best way, but it seems to work ok. I'm not sure if the order that the xs:element
's are processed is guaranteed though. Also, this is an XSLT 2.0 answer tested with Saxon-HE 9.3.0.5 in oXygen.
XML Input (modified the case of Person
to match the schema):
<person>
<property name="address" value="5" />
<property name="firstname" value="1234567890" />
<property name="lastname" value="The BFG" />
</person>
External XSD Schema file (schema.xsd):
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
XSLT 2.0 Stylesheet:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="#all">
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="input">
<xsl:copy-of select="/"/>
</xsl:variable>
<xsl:template match="/*">
<xsl:variable name="firstContext" select="name()"/>
<xsl:variable name="xsdElems" select="document('schema.xsd')/xs:schema/xs:element[@name=$firstContext]/xs:complexType/xs:sequence/xs:element/@name"/>
<xsl:element name="{$firstContext}">
<xsl:for-each select="$xsdElems">
<xsl:variable name="secondContext" select="."/>
<xsl:element name="{$secondContext}">
<xsl:value-of select="$input/*/*[@name=$secondContext]/@value"/>
</xsl:element>
</xsl:for-each>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
XML Output:
<person>
<firstname>1234567890</firstname>
<lastname>The BFG</lastname>
<address>5</address>
</person>
Hope this helps.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…