2012-01-06 112 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