2013-05-09 80 views
0

我有以下XML文件:如何在xml字段上創建另一個字段的屬性?

<generic_etd> 
    <dc.contributor>NSERC</dc.contributor> 
    <dc.creator>gradstudent</dc.creator> 
    <dc.contributor>John Smith</dc.contributor> 
    <dc.contributor.role>Advisor</dc.contributor.role> 
    <dc.date>2013-05-07</dc.date> 
    <dc.format>30 pages</dc.format> 
    <dc.format>545709 bytes</dc.format> 
    <dc.contributor>Jane Smith</dc.contributor> 
    <dc.contributor.role>Committee Member</dc.contributor.role> 
</generic_etd> 

,我想,以轉化成以下使用XSLT 1.0:

<etd_ms> 
    <etd_ms:contributor>NSERC</etd_ms:contributor> 
    <etd_ms:creator>gradstudent</etd_ms:creator> 
    <etd_ms:contributor role="Advisor">John Smith</etd_ms:contributor> 
    <etd_ms:date>2013-05-07</etd_ms:date> 
    <etd_ms:format>30 pages</etd_ms:format> 
    <etd_ms:format>545709 bytes</etd_ms:format> 
    <etd_ms:contributor role="Committee Member">Jane Smith</etd_ms:contributor> 
</etd_ms> 

我可以做etd_ms替代,但我有困難是什麼插入contributor.role行作爲貢獻者行的屬性。我是新的xslt轉換,所以這讓我難住。有什麼建議麼?

這裏是到目前爲止的代碼(我已經離開了開始和結束標記爲簡便起見我也想感謝納文拉瓦特誰提供這種更簡潔版本的代碼,那麼我本來有。):

<xsl:output method="xml" indent="yes" encoding="UTF-8"/> 
<xsl:strip-space elements="*"/> 

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

</xsl:template> 

<xsl:template match="*"> 
    <xsl:choose> 
     <xsl:when test="name()='generic_etd'"> 
      <etd_ms:thesis> 
       <xsl:apply-templates/> 
      </etd_ms:thesis> 
     </xsl:when> 
     <xsl:otherwise> 
      <xsl:variable name="newtag" select="concat('etd_ms:',substring-after(name(),'.'))"/> 
      <xsl:choose> 
       <xsl:when test="contains($newtag, '.')"> 
        <xsl:element name="{substring-before($newtag,'.')}"> 
         <xsl:apply-templates/> 
        </xsl:element> 
       </xsl:when> 
       <xsl:otherwise> 
        <xsl:element name="{$newtag}"> 
         <xsl:apply-templates/> 
        </xsl:element> 
       </xsl:otherwise> 
      </xsl:choose> 
     </xsl:otherwise> 
    </xsl:choose> 
</xsl:template> 

謝謝。

+0

編輯您的文章,幷包括你已經完成 – 2013-05-09 17:14:39

回答

0

我自己設法找出解決方案。基本上,我創建了一個模板,我從原始問題中包含的前一個xslt文件中調用。這裏是使用的模板:

<xsl:template name="contributor-role"> 
    <xsl:param name="element-tag"/> 
    <xsl:choose> 
    <!-- check if the next element is a contributer role --> 
    <xsl:when test="following-sibling::dc.contributor.role[1]"> 
     <xsl:element name="{$element-tag}"> 
     <!-- add the role as an attribute of the current element--> 
     <xsl:attribute name="role"> 
      <xsl:value-of select="following-sibling::dc.contributor.role[1]"/> 
     </xsl:attribute> 
     <xsl:apply-templates/> 
     </xsl:element> 
    </xsl:when> 
    <xsl:otherwise> 
     <!-- else process the element normally --> 
     <xsl:element name="{$element-tag}"> 
     <xsl:apply-templates/> 
     </xsl:element> 
    </xsl:otherwise> 
    </xsl:choose> 
</xsl:template> 
相關問題