This is an example of a grouping problem. If you are using XSLT 1.0, then you need to read up on Muenchian Grouping which is generally the most efficient way of handling such problems.
I am assuming you are grouping serviceAction elements by their name, so you start off by defining a key to look up serviceAction elements by name
<xsl:key name="service" match="t:serviceAction" use="t:name" />
(Note, the t: prefix here is because in your original XML, all the elements are in the namespace="packetware:teleprovision", and so you will need to declare this in your XSLT too. I am using the prefix t for the declaration in this case).
Then, to get the distinct name elements, which form the basis of your group, the expression is as follows:
<xsl:apply-templates select="t:serviceActions/t:serviceAction
[generate-id() = generate-id(key('service', t:name)[1])]" />
This looks at all serviceAction elements, and finds the first one that occurs in the key for the value of its current name.
Then, to get the elements in each group, you can just iterate over the key, like so:
<xsl:for-each select="key('service', t:name)">
Try this XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:t="packetware:teleprovision">
<xsl:output method="text"/>
<xsl:key name="service" match="t:serviceAction" use="t:name" />
<xsl:variable name="quote">"</xsl:variable>
<xsl:template match="/*">
<xsl:apply-templates select="t:serviceActions/t:serviceAction[generate-id() = generate-id(key('service', t:name)[1])]" />
</xsl:template>
<xsl:template match="t:serviceAction">
"<xsl:value-of select="t:name" />": <xsl:text>{</xsl:text>
<xsl:for-each select="key('service', t:name)">
<xsl:if test="position() > 1">,</xsl:if>
"<xsl:number />" : {
"operation": "<xsl:value-of select="t:parameters/t:parameter[t:name='action']/t:value" />",
"value" : "<xsl:value-of select="t:parameters/t:parameter[t:name='new']/t:value" />"
<xsl:text>}</xsl:text>
</xsl:for-each>
}
</xsl:template>
</xsl:stylesheet>
This outputs the following
"usage_state": {
"1" : {
"operation": "add",
"value" : "0ghfgfg"
},
"2" : {
"operation": "add",
"value" : "1ghfgfg"
},
"3" : {
"operation": "add",
"value" : "2ghfgfg"
},
"4" : {
"operation": "add",
"value" : "3ghfgfg"
},
"5" : {
"operation": "add",
"value" : "4ghfgfg"
}
}
Note, in XSLT 2.0, you can use xsl:for-each-group instead of the Muenchian grouping method, to simplify things.