2017-11-07 9 views
0

私は、XMLファイルから数字を抽出し、新しい要素に追加したいです。 は、私が最初に、その新しい情報の後に要素を追加しようとしました。は、どのように私は、XMLファイルにXSLを持つ要素を追加するには?

XML-ファイル:

<products> 
<product> 
    <OrderingInfo> 
     <item name="Part No.">12345 (text)</item> 
     <item name="Part No.">12345IP (text)</item> 
    </OrderingInfo> 
</product> 

<product> 
    <OrderingInfo> 
     <item name="Part No.">001 (text)</item> 
     <item name="Part No.">002 (text)</item> 
    </OrderingInfo> 
</product> 

所望の出力:

<products> 
<product> 
    <OrderingInfo> 
     <item name="Part No.">12345 (text)</item> 
     <item name="Part No.">12345IP (text)</item> 
    </OrderingInfo> 
    <varitems> 
    </varitems> 
</product> 

<product> 
    <OrderingInfo> 
     <item name="Part No.">001</item> 
     <item name="Part No.">002</item> 
    </OrderingInfo> 
    <varitems> 
    </varitems> 
</product> 

しかし、私は要素を追加することが可能である方法を知っているし、その後は使用しないでくださいそれ? これは私が私が探しています主な部分は(追加varitems)上の最初のものである

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output indent="yes" method="xml"/> 
    <xsl:strip-space elements="*"/> 
    <xsl:template match="node()|@*"> 
     <xsl:copy> 
      <xsl:apply-templates select="node()|@*"/> 
     </xsl:copy> 
    </xsl:template> 

    <xsl:template match="OrderingInfo"> 
     <xsl:copy-of select="."/> 
     <varitems></varitems> 
    </xsl:template> 

    <xsl:template match="varitems"> 
     <xsl:copy> 
      <xsl:for-each select="ancestor::product/OrderingInformation/item"> 
       <item> 
        <partno><xsl:value-of select="substring-before(../item[1], ' ')"/></partno> 
        <varno><xsl:value-of select="normalize-space(substring-before(current(),' '))"/></varno> 
        <vartitle><xsl:value-of select="normalize-space(translate(substring-after(current(),' '),'()',''))"/></vartitle> 
       </item> 
      </xsl:for-each> 
     </xsl:copy> 
    </xsl:template> 
</xsl:stylesheet> 

でそれを試してみましたが、その後、それを使用するコードです。 (残りは問題ありません)

答えて

0

要素は、希望の出力でproductの子であり、productテンプレートを使用して直接生成することができます。

<xsl:template match="product"> 
    <xsl:copy> 
     <xsl:apply-templates/> 
     <varitems> 
     </varitems> 
    </xsl:copy> 
</xsl:template> 
+0

私は私のXML所望の出力を編集します。私は ''のみ追加varitemsを望んでいません。それは同じコードですか? – NeunNatter

+0

要件の変更に応じて回答を変更しました。 – tmakita

+0

あなたはそれが唯一の出力にシリアライズされているので、テンプレートで生成された 'varitems'要素に一致するテンプレートを作る傾けます。つまり、あなたのテンプレート 'xsl:template/@ match =" varitems "'は出力に何の影響も与えません。あなたは本当にこのメカニズムを理解していますか? – tmakita

関連する問題