Accessing the value of an input element with XPath in an XSLT
I'm developing a web app for Firefox that has a button that triggers a client-side XSLT transformation of the document's DOM, with a stylesheet fetched via AJAX.
Here's a portion of the XHTML that's going to be transformed:
<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 value
attribute of the first input field, the one with id form_name
.
The XSLT lo开发者_运维问答oks 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 apply the XSLT on the current document
, like so:
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 that the XPath that should do the work:
<xsl:value-of select="input[@id = 'form_name']/@value" />
returns nothing, whereas inspecting the DOM via Firebug shows the input
element's value
property does have a value.
Can anyone help?
EDIT: made clear that the XSLT is applied to the current document
try referencing the input with a slash or dot dot slash
<xsl:value-of select="/input[@id = 'form_name']/@value" />
<xsl:value-of select="../input[@id = 'form_name']/@value" />
One obvious problem:
<xsl:value-of select="input[@id = 'form_name']/@value" />
This must output the value of the @value
attribute of the input
child of the vurrent node.
However, in the provided XML document, the input
child of the element matched by the template, doesn't have a @value
attribute:
Form name <input type="text" id="form_name" />
The only two attributes this input
element has are type
and id
.
Solution: Add a value
attribute to the input element and (given everything else in the XSLT code works OK), the value of this attribute should be output.
For example use:
Form name <input type="text" id="form_name" value="XXXXX" />
This is a hack, but I use it and it works
Add
onBlur="this.setAttribute('value', this.value);"
to every input element.
You can use whatever event you want but onBlur is nice, since it does not generate too much client side overhead.
精彩评论