我想爲別人解決這個問題,並且自己遇到了問題。XSLT選擇當前的特定節點
我有XML:
<Process>
<name>Pro1</name>
<duration>Dur1</duration>
<time>Time1</time>
<name>Pro2</name>
<duration>Dur2</duration>
<time>Time2</time>
<name>Pro3</name>
<duration>Dur3</duration>
<time>Time3</time>
<name>Pro4</name>
<duration>Dur4</duration>
<time>Time4</time>
<name>Pro5</name>
<duration>Dur5</duration>
<time>Time5</time>
</Process>
輸出:
<Process>
<Process_Info>
<name>Pro1</name>
<duration>Dur1</duration>
<time>Time1</time>
</Process_Info>
<Process_Info>
<name>Pro2</name>
<duration>Dur2</duration>
<time>Time2</time>
</Process_Info>
<Process_Info>
<name>Pro3</name>
<duration>Dur3</duration>
<time>Time3</time>
</Process_Info>
<Process_Info>
<name>Pro4</name>
<duration>Dur4</duration>
<time>Time4</time>
</Process_Info>
<Process_Info>
<name>Pro5</name>
<duration>Dur5</duration>
<time>Time5</time>
</Process_Info>
</Process>
使用XSLT:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:variable name ="varProcess" select ="Process"/>
<xsl:template match="Process">
<xsl:element name="Process">
<xsl:for-each select ="name">
<xsl:variable name ="posName" select ="position()"/>
<xsl:element name ="Process_Info">
<xsl:copy-of select ="."/>
<xsl:copy-of select="$varProcess/duration[$posName]"/>
<xsl:copy-of select="$varProcess/time[$posName]"/>
</xsl:element>
</xsl:for-each>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
然而,<duration>
和<time>
節點並不總是存在和<name>
是唯一的保證節點。因此,如果有人錯過了我的position()
選擇失敗。
即使<duration>
和/或<time>
不存在,我如何更改XSLT以允許其工作。
我的理論是,你選擇當前名稱節點下面的兩個節點,如果他們是<duration>
或<time>
他們被複制?但不知道如何實現。
當前輸出導致問題的示例。
輸入:
<Process>
<name>Pro1</name>
<duration>Dur1</duration>
<time>Time1</time>
<name>Pro2</name>
<duration>Dur2</duration>
<time>Time2</time>
<name>Pro3</name>
<duration>Dur3</duration>
<time>Time3</time>
<name>Pro4</name>
<time>Time4</time>
<name>Pro5</name>
<duration>Dur5</duration>
</Process>
輸出:
<Process>
<Process_Info>
<name>Pro1</name>
<duration>Dur1</duration>
<time>Time1</time>
</Process_Info>
<Process_Info>
<name>Pro2</name>
<duration>Dur2</duration>
<time>Time2</time>
</Process_Info>
<Process_Info>
<name>Pro3</name>
<duration>Dur3</duration>
<time>Time3</time>
</Process_Info>
<Process_Info>
<name>Pro4</name>
<duration>Dur5</duration> <!-- Should be in the below process_info -->
<time>Time4</time>
</Process_Info>
<Process_Info>
<name>Pro5</name>
</Process_Info>
</Process>
我給它一小段時間,看看是否有其他用你自己的話說'創造更優雅'的方法,否則將使用它並相應標記。已經明確從您的迴應中瞭解到,並沒有意識到初學者的後續兄弟姐妹:) – Mike 2012-07-18 08:49:18
標記爲答案,因爲您的回覆爲我提供了XSLT所需的工具。我將發佈我的適應性,刪除不需要的默認字段,將字體大小縮小一點。 – Mike 2012-07-18 09:46:25