2016-04-17 53 views
2

我有一個XML,像這樣:XSLT變化值節點

<?xml version="1.0" encoding="UTF-8"?> 
     <earth> 
    <computer> 
      <parts> 
       <cpu>AMD;fast</cpu> 
       <video>GF</video> 
       <power>slow</power> 
       ...others 
      </parts> 
      <owner> 
      <name>Frank</name> 
      <owner> 
      </computer> 

    <earth> 

我想創建XSL轉換(XSL:樣式版本= 「2.0」 的xmlns:XSL =「HTTP ://www.w3.org/1999/XSL/Transform「)。我的預期結果只有當CPU有符號時';' - 在';'之後權力應該變爲價值,如果不存在';'結果應該沒有變化

<earth> 
<computer> 
     <parts> 
      <cpu>AMD</cpu> 
      <video>GF</video> 
      <power>fast</power> 
      ...others 
     </parts> 
     <owner> 
      <name>Frank</name> 
     <owner> 
     </computer> 
<earth> 

嘗試做這樣的事情,但沒有運氣:

<?xml version="1.0" encoding="utf-8"?> 
<xsl:stylesheet version="2.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fn="http://www.w3.org/2005/xpath-functions" 
    exclude-result-prefixes="fn"> 
    <xsl:output encoding="utf-8" method="xml" indent="yes" /> 
    <xsl:template match="@* | node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@* | node()" /> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="parts"> 
     <xsl:choose> 
      <!-- try test if node name equals 'power' if equals them try make logic 
       here, this dont work--> 
      <xsl:when test="name() = 'power'"> 
       <xsl:variable name="text" select="./cpu" /> 
       <xsl:variable name="sep" select="';'" /> 
       <xsl:variable name="powerTable" select="tokenize($text, $sep)" /> 
       <xsl:value-of select="$powerTable[1]" /> 
      </xsl:when> 
      <!--if not 'power' copy node --> 
      <xsl:otherwise> 
       <xsl:copy> 
        <xsl:apply-templates select="@* | node()" /> 
       </xsl:copy> 
      </xsl:otherwise> 
     </xsl:choose> 
    </xsl:template> 
</xsl:stylesheet> 
+1

*「我有一個XML樣式表」*。我們可以知道它是怎麼樣的?因爲發佈到目前爲止只是* XMLs * – har07

+0

我編輯我的文章,我有xml文件,並需要創建xsl將此文件轉換爲新的xml文件,並獲得預期結果 – Wait

+0

您是否試圖編寫XSLT到目前爲止?如果有,請分享並解釋哪部分不按預期工作,或者哪部分不知道如何實施。如果你還沒有,請閱讀關於XSLT的介紹性教程,並嘗試先自己編寫一個教程。祝你好運! – har07

回答

0

我會用下面的模板來實現這一點:

<xsl:template match="parts[contains(cpu,';')]/power"> 
    <power> 
     <xsl:value-of select="../cpu/substring-after(.,';')"/> 
    </power> 
</xsl:template> 

<xsl:template match="cpu[contains(.,';')]"> 
    <cpu> 
     <xsl:value-of select="substring-before(.,';')"/> 
    </cpu> 
</xsl:template> 

<xsl:template match="@* | node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@* | node()" /> 
    </xsl:copy> 
</xsl:template> 

第一個模板匹配power元素是partsparts/power)的直接子元,其中parts有子元素cpu,其中包含字符;parts[contains(cpu,';')])。此模板將輸出power元素,其值爲cpu元素值,字符爲;

第二模板相匹配,一個包含字符;,並輸出cpu元件與初始值,字符;之前cpu元件。

其他模板只是身份模板,我假設你知道目的。

+0

謝謝。它效果很好 – Wait