Accessing input element value with XPath in XSLT

I am developing a web application for Firefox that has a button that triggers a client-side XSLT transformation of a DOM document, with a stylesheet obtained via AJAX.

Here's the XHTML part to be converted:

<html>
<head>
    <title>Static Javascript-based XMR Form Creator</title>
</head>
<body>
    <h1 id="title">Static Javascript-based XMR Form Creator</h1>

    <div class="opt_block" id="main_opts">
        Form name <input type="text" id="form_name" />
        Form cols <input type="text" id="form_cols" size="3" maxlength="3" />
    </div>
    <button id="generate">Generate source</button>
    <textarea rows="20" cols="50" id="xmr_source" ></textarea>
</body>

      

Inside the stylesheet, I want to access the attribute of the value

first input field, with an ID form_name

.

XSLT looks like this:

<xsl:template match="/html/body/div[@id = 'main_opts']" >
    <form>
        <xsl:attribute name="fname">
            <xsl:value-of select="input[@id = 'form_name']/@value" />
        </xsl:attribute>
    </form>
</xsl:template>

      

I am applying XSLT to the current one document

, for example:

var processor = new XSLTProcessor();
processor.importStylesheet(data); // data received via AJAX request
// document is obviously the object representing the current DOM
var result = processor.transformToDocument(document);

      

The problem is the XPath that should do the job:

<xsl:value-of select="input[@id = 'form_name']/@value" />

      

returns nothing, whereas checking the DOM through Firebug shows that the input

element property value

has a value.

Can anyone please help?

EDIT: It is clear that XSLT applies to the current doc

+2


a source to share


3 answers


try referencing the input with a forward slash or dotted slash



<xsl:value-of select="/input[@id = 'form_name']/@value" />
<xsl:value-of select="../input[@id = 'form_name']/@value" />

      

+1


a source


One obvious problem:

<xsl:value-of select="input[@id = 'form_name']/@value" />

      

This should output the value of the vurrent node @value

child attribute input

.

However , in the provided XML document, the child of the input

matched element has no attribute @value

:

   Form name <input type="text" id="form_name" />  

      



The only two attributes for this element input

are type

and id

.

Solution : Add an attribute value

to the input element and (if everything else in the XSLT code works fine) the value of that attribute should be output.

For example use :

   Form name <input type="text" id="form_name" value="XXXXX" />  

      

+1


a source


This is a hack but i use it and it works

Add to

onBlur="this.setAttribute('value', this.value);"

      

for each input element.

You can use any event you want, but onBlur is a good thing as it doesn't create too much client-side overhead.

+1


a source







All Articles