Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating xml attribute value with XSL

Tags:

xml

xslt

I am new to using XSL. I am trying to tranform data entered into a datacapture template and generate an xml file. I am capturing data that should be attribute values. I know that my paths are correct but I get an error during generation. Help!

<!-- <xsl:value-of select='odnodes/node/comments'/> -->
<node name="<xsl:value-of select='odnodes/node/name'/>" 
      host="<xsl:value-of select='odnodes/node/host'/>" 
      port="<xsl:value-of select='odnodes/node/port'/>" 
/>

The end result would look something like this:

<!-- uat server - added 2/7/2013 -->
<node name="webserver_uat" host="192.168.1.1" port="20014" />
like image 876
Nicholas Anderson Avatar asked Jun 23 '26 19:06

Nicholas Anderson


1 Answers

Attribute Value Templates are your friend here. The correct syntax for what you are trying to achieve is

<node name="{odnodes/node/name}" 
      host="{odnodes/node/host}" 
      port="{odnodes/node/port}" />

The curly braces here indicate it is an expression to be evaluated, as opposed output literally.

Note, you could also use xsl:attribute to create attribute:

<node>
   <xsl:attribute name="name"><xsl:value-of select="odnodes/node/name" /></xsl:attribute>
   <xsl:attribute name="host"><xsl:value-of select="odnodes/node/name" /></xsl:attribute>
   <xsl:attribute name="port"><xsl:value-of select="odnodes/node/name" /></xsl:attribute>
</node>

But as you can see this is more verbose, and you would only really need to do it this way if you wanted 'conditional' attributes. (i.e You wrap one of the attributes in an xsl:if, for example, or vary the attribute name depending on a value in the input XML).

like image 190
Tim C Avatar answered Jun 28 '26 03:06

Tim C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!