1

I have an xml like this:

<root> <row col1="value1" col2="value2" ...... coln="valuen"/> <row col1="value1" col2="value2" ...... coln="valuen"/> . . . <row col1="value1" col2="value2" ...... coln="valuen"/> </root>

How do I convert this into a table attribute names as column names and attribute values as column values?

1 Answer 1

3

This will work, assuming that each row has the same number of attributes:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="html" />

    <xsl:template match="/root">
        <table>
            <tbody>
                <tr>
                    <xsl:apply-templates select="row[1]" mode="header"/>
                </tr>
                <xsl:apply-templates select="row" mode="rows"/>
            </tbody>
        </table>
    </xsl:template>

    <xsl:template match="row" mode="header">
        <xsl:for-each select="attribute::*">
            <th><xsl:value-of select="local-name(.)" /></th>
        </xsl:for-each>
    </xsl:template>

    <xsl:template match="row" mode="rows">
        <tr>
            <xsl:for-each select="attribute::*">
                <td><xsl:value-of select="." /></td>
            </xsl:for-each>
        </tr>
    </xsl:template>

</xsl:stylesheet>

If there might be additional attributes that don't represent column values, you'd need to filter out those by checking the name or something.

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.