使用XSLT可以很好地實現從XML這樣的代碼生成。如果您安裝了libxslt,則可以使用xsltproc執行轉換。在構建過程中將其作爲預構建步驟以生成源代碼。
如何:
structs.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="zone">
<xs:complexType>
<xs:sequence>
<xs:element name="Var_name" type="xs:string"/>
<xs:element name="var_value" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="zone2">
<xs:complexType>
<xs:sequence>
<xs:element name="Var_name" type="xs:string"/>
<xs:element name="var_value" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
makestructs.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.0">
<xsl:output method="text" />
<xsl:template match="/">
<xsl:for-each select="/xs:schema/xs:element">
struct <xsl:value-of select="@name" /> {
<xsl:for-each select="xs:complexType/xs:sequence/xs:element">
<xsl:choose>
<xsl:when test="@type = 'xs:string'">
char*
</xsl:when>
<xsl:when test="@type = 'xs:decimal'">
float
</xsl:when>
</xsl:choose>
<xsl:value-of select="@name" />;
</xsl:for-each>
};
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
樣式表是縮進以提高可讀性。但你會想要刪除一些空白,所以它不會出現在輸出中。
如果你想C兼容,如果你使用C++或者一對'char *'和'int',我會建議將xs:string映射到更好的結構,'std :: string'。 – 2009-12-19 13:41:43
您的意思是:如何將C++抽象語法樹映射到XML結構? – xtofl 2010-11-06 09:04:58