We help IT Professionals succeed at work.

Need to add an attribute to an XML element, using XSLT

fsyed
fsyed asked
on
Dear fellow developers:

I have an XML document that has the structure listed below.  Each <collection>  element has several <volume> elements, each <volume> element contains several <book> elements, each <book> element contains several <chapter> elements, and each <chapter> element contains several <quote> elements.  What I would like to do is include an "id" attribute at the end of the attribute list for the <quote> element.  For now, I'd like to leave the value of the "id" attribute to be 0 (i.e. id="0").   How would I do this?  

Thanks in advance to all who reply.

<?xml version="1.0" encoding="UTF-8"?>
<collection name="collection title">
   <volume number="1">
      <book number="1" title="book title">
         <chapter number="1" title="chapter title">
             <quote number="1" grade="authentic" reference="Volume 1, Book 1, Chapter 1, Number 1">
               <meta>
                  <description></description>
               </meta>
               <narrator>John Doe</narrator>
               <matn>
                  <matn-text></matn-text>
                  <matn-footnote></matn-footnote>
               </matn>
               <link>
                  <key></key>
               </link>
            </quote>
            ...
          </chapter>
          <chapter>
          ...
          </chapter>
          ...
        </book>
        ...
     </volume>
     ...
   </chapter>

Open in new window

Comment
Watch Question

Information Architect
Top Expert 2006
Commented:
This stylesheet will leave your XML intact, but adds a @id at every quote element
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">
    <xsl:template match="node()">
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:apply-templates select="node()"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="quote">
        <xsl:copy>
            <xsl:copy-of select="@*"/>
            <xsl:attribute name="id">
                <xsl:text>0</xsl:text>
            </xsl:attribute>
            <xsl:apply-templates select="node()"/>
        </xsl:copy>
    </xsl:template>
</xsl:stylesheet>

Open in new window

Author

Commented:
Thanks very much for your prompt reply.  Your solution worked!  Full points!

Author

Commented:
I really appreciate your help.  Thanks again for everything!
Gertone (Geert Bormans)Information Architect
Top Expert 2006

Commented:
welcome