1

Okay, I'm trying to be able to dynamically set the input attributes via an XML tag. For example:

<text name='text_name' value='text_value'>text_display</text>

I want to run a foreach to make it so name, value, or any other attribute in <text> will be inserted as an attribute for the HTML input and use the value of the <text> as the label/placeholder.

<xsl:for-each select="text">
    <label><xsl:value-of select="." /></label>
    <input type='textfield' placeholder='{.}' />
</xsl:for-each>

Now I know I can use:

<xsl:for-each select="@*"> 

but I don't know how to insert that into the input tag.

Thanks in advance for any advice.

1
  • Can you give an example of input and the desired output? Commented Nov 7, 2013 at 4:10

1 Answer 1

2

Try and use push focused (rather than pull-focused) XSLTs with more apply-templates and less for-each statements.

There is nothing that says the definition of an element or its attributes must be in the same template. So when you make the template for the <text> element, you can just create the <input> element and apply-templates over all of the attributes.

<xsl:template match="text">
 <input>
  <xsl:apply-templates select="@*"/>
  <label><xsl:value-of select="." /></label>
 </input>
</xsl:template>

Secondly, what you are trying to do is literally copy the attributes into the new document, so rather than recreate them, just copy them, like so:

<xsl:template match="text/@*">
  <xsl:copy/>
</xsl:template>

So, here is a complete stylesheet...

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

<xsl:template match="/texts">
 <xsl:apply-templates />
</xsl:template>

<xsl:template match="text">
 <input>
  <xsl:apply-templates select="@*"/>
  <label><xsl:value-of select="." /></label>
 </input>
</xsl:template>

<xsl:template match="text/@*">
  <xsl:copy/>
</xsl:template>

</xsl:stylesheet>

... when applied to this input XML document...

<texts>
  <text name='text_name' value='text_value'>text_display</text>
  <text name='text_name2' value='text_value2'>other_display</text>
</texts>

... gives this result XML

<input name="text_name" value="text_value">
    <label>text_display</label>
</input>
<input name="text_name2" value="text_value2">
    <label>other_display</label>
</input>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, I'm still new to XSLT so I appreciate the link and advice.

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.