2012-01-06 82 views
1

我正在处理XSLT文件以将表示XML的文档转换为SQL命令。该XML描述两个表的列和每一行的数据结构如下:XSLT动态属性里面每个

<Table> 
<ObjectAttributes> 
    <AttributeDetail> 
    <Name>COLNAME1</Name> 
    ... 
    </AttributeDetail> 
    <AttributeDetail> 
    <Name>COLNAME2</Name> 
    ... 
    </AttributeDetail> 
    ... 
</ObjectAttributes> 
<Record RowID="00001"> 
    <Attributes> 
    <Attr> 
     <AttrName>COLNAME1</AttrName> 
     <AttrValue>VALUE</AttrValue> 
    </Attr> 
    <Attr> 
     <AttrName>COLNAME2</AttrName> 
     <AttrValue>VALUE</AttrValue> 
    </Attr> 
    ... 
    </Attributes> 
</Record> 
<Record RowID="00002"> 
    <Attributes> 
    <Attr> 
     <AttrName>COLNAME1</AttrName> 
     <AttrValue>VALUE</AttrValue> 
    </Attr> 
    <Attr> 
     <AttrName>COLNAME2</AttrName> 
     <AttrValue>VALUE</AttrValue> 
    </Attr> 
    ... 
    </Attributes> 
</Record> 
... 
</Table> 

我写了下面的XSLT创建INSERT命令:

<xsl:for-each select="/Table/Record"> 
    <xsl:variable name="ThisRecord" select="."/> 
    <Command> 
    INSERT INTO <xsl:value-of select="../ObjectName"/> 
     (ROWID, 
     <xsl:for-each select="../ObjectAttributes/AttributeDetail"> 
     <xsl:value-of select="Name"/> 
     <xsl:if test="position() != last()"> 
      <xsl:text>, </xsl:text> 
     </xsl:if> 
     </xsl:for-each>) 
     VALUES 
     (<xsl:value-of select="@RowID"/>, 
     <xsl:for-each select="../ObjectAttributes/AttributeDetail"> 
     <xsl:text>'</xsl:text><xsl:value-of select="$ThisRecord/Attributes/Attr/AttrValue[../AttrName='COLNAME1']"/><xsl:text>'</xsl:text> 
     <xsl:if test="position() != last()"> 
      <xsl:text>, </xsl:text> 
     </xsl:if> 
     </xsl:for-each>) 
    </Command> 
</xsl:for-each> 

这个工程除了事实巨大我正在努力想出如何与将导致从值替换值AttrName =“”:

<xsl:value-of select="Name"/> 

我试图用一个变量替换,但THI s没有工作:

<xsl:variable name="ThisAttr" select="Name"/> 
<xsl:value-of select="$ThisRecord/Attributes/Attr/AttrValue[../AttrName='$ThisAttr']"/> 

如何动态地填写此属性?

谢谢!

+0

你就不能换每遍/录音/属性两次,一次为属性的名称,以及第二次为属性值? ObjectAttributes中的名称是否与Attributes部分中的AttrName相同? – dash 2012-01-06 21:04:20

+0

这会工作,但我希望将每个/ Record/Attributes匹配到ObjectAttributes,以确保记录中的属性存在于对象中。 – Paul 2012-01-06 21:07:30

+1

够公平的!下面的XPath表达式应该适用于你:$ ThisRecord/Attributes/Attr [AttrName = $ ThisAttr]/AttrValue - 你只需要你的AttrName检查错误的地方,因为你想说的是找到我的attr与一个孩子attrName = $ ThisAttr名称,然后选择AttrValue。 – dash 2012-01-06 21:10:53

回答

2

您可以current()引用当前上下文节点:

<xsl:value-of 
    select="$ThisRecord/Attributes/Attr[AttrName=current()/Name]/AttrValue"/> 

我要指出,你的变量方法将有AttrName='$ThisAttr'工作没有围绕可变参考报价。你在字符串$ThisAttr(即不引用任何变量)上完全匹配;你应该使用AttrName=$ThisAttr(不含引号)。

也就是说,使用current()是更好的解决方案。

(需要注意的是,这样不需要回溯我也重新安排表达步骤。)

+0

+1 - 打我也是这样虽然我打算使用变量而不是当前();-) – dash 2012-01-06 21:13:02

+0

感谢您的提示;这就是我所追求的。重新安排也是一个好主意。 – Paul 2012-01-06 21:17:27