2017-10-11 54 views
0

我有這樣插入基於另一元件

<document startnum="1" language="en-US"> 
<meta> 
<categories> 
<category medicalbranch="surgery"> 
</category> 
</categories> 
<doctitle>Traumatology for the Physical Therapist</doctitle> 
<relatedobjects> 
<relpdfio/> 
</relatedobjects> 
<publisher> 
<publishername>Georg Thieme Verlag</publishername> 
<copyright>Georg Thieme Verlag</copyright> 
</publisher> 
</meta> 

一個輸入XML文件上輸出XML應該像下面

<document startnum="1" language="en-US"> 
<meta> 
<categories> 
<category medicalbranch="surgery"> 
</category> 
</categories> 
<isbn type="print"> </isbn> 
<isbn type="online"> </isbn> 
<materialid/> 
<metadata type="searchlevel"/> 
<doctitle>Traumatology for the Physical Therapist</doctitle> 
<relatedobjects> 
<relpdfio/> 
</relatedobjects> 
<publisher> 
<publishername>Georg Thieme Verlag</publishername> 
<copyright>Georg Thieme Verlag</copyright> 
</publisher> 
</meta> 

我需要上述插入提到4個元件每當「新元素meta「元素在源代碼中不包含」isbn「。

我已經寫了XSLT象下面這樣:

<xsl:template match="meta"> 
    <xsl:if test="node[not(isbn)]"> 
     <xsl:element name="isbn"> 
      <xsl:attribute name="type">print</xsl:attribute> 
      <xsl:text>&#xA0;</xsl:text> 
     </xsl:element><xsl:text>&#xa;</xsl:text> 
     <xsl:element name="isbn"> 
      <xsl:attribute name="type">online</xsl:attribute> 
      <xsl:text>&#xA0;</xsl:text> 
     </xsl:element> 
     <xsl:text>&#xa;</xsl:text>   
     <xsl:element name="materialid"></xsl:element><xsl:text>&#xa;</xsl:text> 
     <xsl:element name="metadata"> 
      <xsl:attribute name="type">searchlevel</xsl:attribute></xsl:element> 
     <xsl:text>&#xa;</xsl:text> 
     <!--<xsl:text disable-output-escaping="yes">-\-&gt;</xsl:text>--> 
     <xsl:apply-templates select="@*|node()"/> 
     <xsl:text>&#xa;</xsl:text> 
    </xsl:if> 
    <xsl:copy> 
     <xsl:apply-templates select="node() | @*"/> 
    </xsl:copy> 
</xsl:template> 

能否請您幫助我們解決這個問題。

回答

0

開始與身份轉換模板

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

,然後決定你想要的categories元素之後插入新的元素,例如如

<xsl:template match="meta[not(isbn)]/categories"> 
    <xsl:next-match/><!-- copies the categories element with the identity transformation template --> 
    <isbn type="print"> </isbn> 
    <isbn type="online"> </isbn> 
    <materialid/> 
    <metadata type="searchlevel"/> 
</xsl:template> 
+0

感謝您的迴應Martin。它在我的文件中工作。 – Sumathi

+0

我想保持自我結束標籤,如 。你能幫助我,如何爲它編寫代碼。 – Sumathi

+0

XSLT沒有定義空元素是否被序列化爲例如''或''所以我恐怕這是XSLT以外的任務。在http://xsltransform.net/3MvmrAL中,您的示例輸入似乎可以通過''結果正常轉換,但通常取決於XSLT處理器/序列化程序。 –