'XSL - Unable to get all child nodes
I am trying to generate a custom schema (XSD file) using a XSL file but the XSL is not picking up all the data elements from the XML input which I am providing. Please see below:
XML input:
<?xml version="1.0" encoding="utf-8"?>
<Employees>
<Employee>
<Data>
<Name>Rob</Name>
<Age>20</Age>
</Data>
</Employee>
<Employee>
<Data>
<Name>Sean</Name>
<Age>50</Age>
<Department>Accounts</Department>
</Data>
</Employee>
</Employees>
XSL:
<xsl:template match="Data[*]">
<xs:element name="Data" minOccurs="1">
<xs:complexType>
<xs:all minOccurs="0">
<xsl:call-template name="DataChildren"/>
</xs:all>
</xs:complexType>
</xs:element>
</xsl:template>
<xsl:template name="DataChildren">
<xsl:for-each select="*">
<xsl:choose>
<xsl:when test="local-name() = 'Gender'">
<xs:element name="Gender" type="Gender" minOccurs="0" />
</xsl:when>
<xsl:when test="local-name() = 'Age'">
<xs:element name="Age" type="Age-empty" minOccurs="0" />
</xsl:when>
<xsl:otherwise>
<xs:element name="{local-name()}" type="xs:string" minOccurs="0" />
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
XSD output:
<xs:element name="Data" minOccurs="1">
<xs:complexType>
<xs:all minOccurs="0">
<xs:element name="Name" type="xs:string" minOccurs="0"/>
<xs:element name="Age" type="xs:string" minOccurs="0"/>
</xs:all>
</xs:complexType>
</xs:element>
If you can see the XSD output above its missing the Department node. Looks like its not looping through all the child Employee elements rather it only picks up the nodes available in the first child node. Please help.
Solution 1:[1]
This seems to be completely misguided. Your stylesheet is written with knowledge of the structure of the XML - that is, knowledge of the schema you are trying to generate. Perhaps there are some aspects of the schema you know in advance and other aspects that you want to infer, but if that's the case, you need to explain it to us.
In addition, your code is making no attempt to look at all the Data elements, or at all the Employee elements, to discover what they have in common. You can only construct a schema for Data elements if you look at all the Data elements in the input to infer a type that they all conform to.
Finally, there are plenty of tools around for constructing a schema from an instance document. Why aren't you using them?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Michael Kay |
