Transforming HTML with XSL and Modifying Form Attributes
I would like to parse an HTML document and replace the action attribute of all forms and add some hidden fields using XSL. Can anyone show some XSL examples that can do this?
First you need to well-form your HTML (at least a transient one), although XHTML is best recommended. Some XSLT processors may accept invalid HTML, but this is not a rule.
To try the example below, you can download this small Microsoft command line application .
A quick and dirty XSLT example for what you need (example-xslt.xsl):
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="*">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="form[@action='foo']">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:attribute name="action">non-foo</xsl:attribute>
<input type="hidden" name="my-hidden-prop" value="hide-foo-here"/>
<xsl:apply-templates select="*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
And the corresponding XML example (example.xml).
<?xml version ="1.0"?>
<?xml-stylesheet type="text/xsl" href="example-xslt.xsl"?>
<html>
<head></head>
<body>
<form action="foo">
</form>
<form action="other">
</form>
</body>
</html>
You can start with this tutorial
But keep in mind that it usually XSLT
requires correct input XML
, HTML
not always well-formed
Thinking about gurin's answer: One possible XSLT-based way for HTML is to use the option to transform to XHTML, apply XSLT to XHTML, but use xsl:output[@method="html"]
to return HTML. The @doctype-system
and attributes @doctype-public
allow you to provide a doctype declaration in the output file.
I don't have any sample files for shahbhat, but the general approach is simple from an XSLT perspective: start with an identity transformation and add action attributes to templates to override them however you want. To add hidden fields, I suspect that the simplest way would be to create a template explicitly for an element form
as an identity transformation, but with additional elements inside it that are rendered as well. I think Fernando Migeles just posted an example.