如何使用 XSL 翻译 C 结构中的 XML 文档

How to translate an XML document in C struct using XSL

我有 XML 文本格式有点像这样:

<root>
  <struct1>
     <el1 type="INT32" descript="Element No.1">0</el1>
     <el2 type="FLOAT32" descript="element No. 2</el2>
  </struct1>

  <struct2>
     <el3 type="INT32" descript="Element No.3">0</el3>
     <el4 type="STRING32" descript="element No. 4</el4>
  </struct2>

  <struct3>
     <el5 type="INT32" descript="Element No.5">0</el5>
     <el6 type="FLOAT32" descript="element No. 6</el6>
  </struct3>
</root>

我想使用 XSLT 将其翻译成如下所示的 C 代码:

/*************************
* legal blah blah
************************************************************************/

#ifndef ROOT_H
#define ROOT_H

typedef struct
{
   INT32 el1;
   FLOAT32 el2;
} root_struct1_t

typedef struct
{
   INT32 el3;
   STRING32 el4;
} root_struct2_t

typedef struct
{
   INT32 el5;
   FLOAT32 el6;
} root_struct3_t

#endif

要求是头文件将使用与根元素相同的名称,但全部大写并附加一个“_H”(在我的示例中,"root" 因此头文件保护将是 ROOT_H. 合法的 blah blah 注释总是放在文件的头部。 "level 1" 元素(根的子元素)必须被翻译为 "typedef struct {...} X_Y_t where X is the root element name, Y is the element name, and the '_t" 常量文本。 这些子元素的子元素使用元素名称进行翻译,类型由 "type" 属性值给出。

是否有 XSL 示例说明如何执行此类操作?

我找到的所有示例中,要翻译的元素的名称对于所有元素都是相同的(如 <prop name="blahblah" type="moreblah" />。这对我不起作用。

这个问题的输出端与其说是我问题的对象,不如说是"how do I extract the name of an element and some of the attributes and reuse them in the output?"

使用 XSLT 1.0:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="text" omit-xml-declaration="yes" encoding="UTF-8" indent="no" />

    <xsl:template match="/*">
        <xsl:variable name="smallcase" select="'abcdefghijklmnopqrstuvwxyz'" />
        <xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />
#ifndef <xsl:value-of select="concat(translate(local-name(), $smallcase, $uppercase), '_H')" />
#define <xsl:value-of select="concat(translate(local-name(), $smallcase, $uppercase), '_H')" />

    <xsl:for-each select="child::*">
    typedef struct {
        <xsl:for-each select="child::*">
            <xsl:value-of select="@type" /> <xsl:text> </xsl:text> <xsl:value-of select="local-name()" />;
        </xsl:for-each>
    } <xsl:value-of select="concat(../local-name(), '_', local-name(), '_t')" />    
    <xsl:text>        
    </xsl:text>
    </xsl:for-each>

#endif
    </xsl:template>


</xsl:transform>

XSLTranform

这里的基本思想是匹配模板中的任意根节点,然后使用child::轴进行迭代。