0

I need to add attribute and new node to existing node

example :

<doc>
  <a></a>
  <a></a>
  <a></a>
  <d></d>
  <a></a>
  <f></f>
</doc>

what i need is add now attrinute to <a> node and add new node inside a node.

so the output would be,

<doc>
  <a id='myId'> <new_node attr="myattr"/> </a>
  <a id='myId'> <new_node attr="myattr"/> </a>
  <a id='myId'> <new_node attr="myattr"/> </a>
  <d></d>
  <a id='myId'> <new_node attr="myattr"/> </a>
  <f></f>
</doc>

I wrote following code to do this task,

<xsl:template match="a">

        <xsl:apply-templates select="@*|node()"/>
        <xsl:copy> 
            <xsl:attribute name="id">
                <xsl:value-of select="'myId'"/>
            </xsl:attribute>      
        </xsl:copy>    

         <new_node>
               <xsl:attribute name="attr">
                   <xsl:value-of select="'myattr'"/>
               </xsl:attribute>
         </new_node>
</xsl:template>

this code adds the new attribute and new node as expected but the problem is it only adds to the first node and it do not compile after this and five following message in oxygen editor. ' An attribute node (id) cannot be created after a child of the containing element.

How can I solve this issue ?

1 Answer 1

1

You are on the right lines, but you need to make sure any child nodes are added AFTER any attributes. Attributes must added first, before any child nodes.

Try this template

<xsl:template match="a">
    <xsl:copy> 
        <xsl:apply-templates select="@*"/>
        <xsl:attribute name="id">
            <xsl:value-of select="'myId'"/>
        </xsl:attribute>      
        <xsl:apply-templates select="node()"/>
        <new_node>
           <xsl:attribute name="attr">
               <xsl:value-of select="'myattr'"/>
           </xsl:attribute>
        </new_node>
    </xsl:copy>    
</xsl:template>

Actually, you can simplify this somewhat, and write out the attribute directly. Try this too

<xsl:template match="a">
    <a id="myId"> 
        <xsl:apply-templates select="@*|node()"/>
       <new_node attr="myattr" />
    </a>    
</xsl:template>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.