How to transform XML data from child elements to attributes?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Philip Cooper

    How to transform XML data from child elements to attributes?

    I'm new to XSL and need to know how to transform some XML structured like this:
    Code:
    <table>
        <contents>
            <DATA>Section 1</DATA>
            <DATA>Chapter 1</DATA>
            <DATA>Part 1</DATA>
        </contents>
        <page>
            <DATA>5</DATA>
            <DATA>15</DATA>
            <DATA>24</DATA>
        </page>
        <level>
            <DATA>1</DATA>
            <DATA>2</DATA>
            <DATA>3</DATA>
        </level>
    </table>
    Into this:
    Code:
    <toc>
        <tocentry level="1" page="5">Section 1</tocentry>
        <tocentry level="2" page="15">Chapter 1</tocentry>
        <tocentry level="3" page="24">Part 1</tocentry>
    </toc>
    Essentially I want to make the child elements of the 'page' and 'level' elements into attributes of the child elements of the 'contents' element (so as to generate a table of contents for an online text).
    Last edited by jkmyoung; Nov 16 '10, 05:26 PM.
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    Basically, you'll be using the position function.

    Code:
    <xsl:for-each select="//contents/Data">
      <tocentry level="{//level/Data[position()=position(current())]" ....>
    I can't remember if this works for all XSLT compilers. You may need to use
    <xsl:variable name="pos" select="positio n()"/>
    and then have ...Data[position()= $pos]

    Also you may have to explicitly declare the attributes depending on compiler.

    Comment

    Working...