0

As the reverse case of this post, how it's possible to transform content of an XML document to array using XSLT.

For this:

<Records>
    <item>value1</item>
    <item>value2</item>
    <item>value3</item>
    <item>value4</item>
    <item>value5</item>
</Records> 

The desired result is something like this:

[value1, value2, value3, value4, value5]

What's the idea?

Community
  • 1
  • 1
Eilia
  • 11
  • 1
  • 3
  • 17

1 Answers1

0

Hope this helps..

    <?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl">
  <xsl:output method="text"/>
  <xsl:template match="/">
    <xsl:variable name="countItems" select="count(Records/item)"/>
    [<xsl:for-each select="Records/item">
      <xsl:value-of select="."/>
      <xsl:choose>
        <xsl:when test="position()=$countItems"/>
        <xsl:otherwise>,</xsl:otherwise>
      </xsl:choose>
    </xsl:for-each>]
  </xsl:template>
</xsl:stylesheet>

XSLT 1.0 can be used to generate a resultant xml,text or HTML file from the source xml file. You can get the resultant data from the file created via XSLT

Saurav
  • 592
  • 4
  • 21
  • Thanks for that, it works. But I think it is not what I'm looking for. One more questions, is there any built-in array structure in XSLT. In fact, I want to manipulate the array as a data structure w.r.t its index. Is this result capable of doing that? Any idea? – Eilia Jan 20 '15 at 07:43
  • Well XSLT works on only xml structure data. What you can do is create a variable within xslt that contains a key/value pair and then on that variable you can find a value using the key – Saurav Jan 20 '15 at 07:46
  • Thanks for the answer. I'll try for that. Of course, this (http://stackoverflow.com/questions/11076920/implementing-key-value-concept-in-xslt) seems to be the solution for that. – Eilia Jan 20 '15 at 07:57
  • @Saurav, are you sure about it? I can see an extra comma getting aded at the end.. – Lingamurthy CS Jan 20 '15 at 08:51