Guest TheBsEr Posted March 31, 2010 Share Posted March 31, 2010 Hi, I would like to change the formatting of an XML file to a different format by using XSLT. For example, <?xml version="1.0"?><root> <row> <id>1</id> <fname>Dan</fname> <lname>Wahlin</lname> </row> <row> <id>2</id> <fname>Heedy</fname> <lname>Wahlin</lname> </row> <row> <id>3</id> <fname>Danny</fname> <lname>Wahlin</lname> </row> <row> <id>4</id> <fname>Jeffery</fname> <lname>Wahlin</lname> </row></root> And change to this format. <?xml version="1.0"?><root> <row id="1" fname="Dan" lname="Wahlin"/> <row id="2" fname="Heedy" lname="Wahlin"/> <row id="3" fname="Danny" lname="Wahlin"/> <row id="4" fname="Jeffery" lname="Wahlin"/></root> And vice versa. Also, how can I view the output as an XML format? I used w3schools editor and tried several things, but it seems their output is in html? (as in I won't see the <row id="1" fname="Dan" lname="Wahlin"> etc but instead as "1 Dan Wahlin". Or I might be doing something wrong.If someone could help me with the XSLT code, it would be greatly appreciated. Thanks in advance! Link to comment Share on other sites More sharing options...
Martin Honnen Posted April 1, 2010 Share Posted April 1, 2010 Here is a stylesheet that transforms the child elements of 'row' elements into attributes: <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:strip-space elements="*"/> <xsl:output method="xml" indent="yes"/> <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> <xsl:template match="row/*"> <xsl:attribute name="{name()}"> <xsl:value-of select="."/> </xsl:attribute> </xsl:template></xsl:stylesheet> And the following stylesheet reverses transformation and transforms attributes into child elements: <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:strip-space elements="*"/> <xsl:output method="xml" indent="yes"/> <xsl:template match="@* | node()"> <xsl:copy> <xsl:apply-templates select="@* | node()"/> </xsl:copy> </xsl:template> <xsl:template match="row/@*"> <xsl:element name="{name()}"> <xsl:value-of select="."/> </xsl:element> </xsl:template></xsl:stylesheet> As for running XML to XML transformations in the browser or with that w3schools editor, I don't think you will get far that way. Consider to use an XML editor (or XML/XSLT plugin to your favourite IDE or code editor) or consider to use an XSLT processor with a command line interface where you can transform to the console window or to a file. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.