kumar
kumar

Reputation: 389

how to capture the name of the node and replace variable with value

I am trying to find a way to get the name of the node and edit it by replacing the varaible with value.

Example:

<mbean code="abc.def.ghi" name="com.ijk.lmn:name=@value1@"> 
    <attribute name="storename">value</attribute> 
    <depends optional-attribute-name="bookname">value2</depends> 
    <attribute name="Type">ebook</attribute> 
    <attribute name="Properties"> 
    bookName=value3
    booktype=value4
</mbean>

Expected output:

<mbean code="abc.def.ghi" name="com.ijk.lmn:name=newvalue"> 
    <attribute name="storename">value</attribute> 
    <depends optional-attribute-name="bookname">value2</depends> 
    <attribute name="Type">ebook</attribute> 
    <attribute name="Properties"> 
    bookName=value3
    booktype=value4
</mbean>

I have tested with this xsl code, but some how its not caprturing what i wanted to:

<xsl:template match="mbean[@name]">
    <xsl:copy>  
    <xsl:apply-templates select="@*"/>
    <xsl:analyze-string select="." regex="([\w.]+)=@(.*?)@">
        <xsl:matching-substring>    
            Value1: <xsl:value-of select="regex-group(1)"/>
            Value2: <xsl:value-of select="regex-group(2)"/>     
        </xsl:matching-substring>
        <xsl:non-matching-substring>
            <xsl:value-of select="."/>
        </xsl:non-matching-substring>
    </xsl:analyze-string>
    </xsl:copy>    
</xsl:template> 

I am not changing any thing in elements, but i am changing the name of node.

Upvotes: 0

Views: 364

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167696

That looks like you want to write a template for the name attribute of an mbean element e.g.

<xsl:template match="mbean/@name">
  <xsl:variable name="tokens" select="tokenize(., '=')"/>
  <xsl:attribute name="{node-name(.)}" select="concat($tokens[1], '=', 'newvalue')"/>
</xsl:template>

I have used a string literal as the new value, of course instead of doing that you could look up the value.

If you have an external document new-values.xml with e.g.

<values>
  <value key="com.ijk.lmn:name">new value</value>
</values>

then define a global parameter

<xsl:param name="value-url" select="'new-values.xml'"/>

a global variable

<xsl:variable name="value-doc" select="doc($value-url)"/>

and a key

<xsl:key name="kv" match="value" use="@key"/>

and then use

<xsl:template match="mbean/@name">
  <xsl:variable name="tokens" select="tokenize(., '=')"/>
  <xsl:attribute name="{node-name(.)}" select="concat($tokens[1], '=', key('kv', $token[1], $value-doc))"/>
</xsl:template>

Upvotes: 1

Related Questions