Home > Back-end >  xslt add processing instruction after element
xslt add processing instruction after element

Time:04-27

In the following XML :

   <?xml version="1.0" encoding="utf8" ?>
<Output>
    <Error>
        <Status>0</Status>
        <Details>No errors</Details>
    </Error>
    <Synopsis>
        <Count>451</Count>
    </Synopsis>
    <BankAccounts>
        <BankAccount AcctNo="103" CustName="Frank" BalanceAmount="" Inactive="N" NoOfAccounts="1" >
            <Addresses>
                <Address>ABC</Address>
                <Address>XYZ</Address>
            </Addresses>
        </BankAccount>
        <BankAccount AcctNo="101" CustName="Jane" BalanceAmount="10005" Inactive="N" NoOfAccounts="1" >
            <Addresses>
                <Address>LMN</Address>
                <Address>QWE</Address>
            </Addresses>
        </BankAccount>
        
    </BankAccounts>
</Output>

I would like to add a Processing instruction AFTER Synopsis and BEFORE BankAccounts:

 <?xml-multiple BankAccount
        ?>

Tried with following XSLT but it is inserting PI Inside 'BankAccounts' How do I do this using XSLT ?

<xsl:template match="BankAccounts">
    <xsl:copy>
        <xsl:processing-instruction name="xml-multiple">
            BankAccount
        </xsl:processing-instruction>
        
        <xsl:apply-templates select="@*|node()"/>
        
    </xsl:copy>
</xsl:template>

CodePudding user response:

If you want the processing instruction to appear before BankAccounts then write it to the output before copying BankAccounts:

<xsl:template match="BankAccounts">
    <xsl:processing-instruction name="xml-multiple">BankAccount</xsl:processing-instruction>
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

In XSLT 2.0 or higher you could shorten this to:

<xsl:template match="BankAccounts">
    <xsl:processing-instruction name="xml-multiple">BankAccount</xsl:processing-instruction>
    <xsl:next-match/>
</xsl:template>

(assuming you have the identity transform template or equivalent in place).


Or - in any version - you could do simply:

<xsl:template match="BankAccounts">
    <xsl:processing-instruction name="xml-multiple">BankAccount</xsl:processing-instruction>
    <xsl:copy-of select="."/>
</xsl:template>
  • Related