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?

1
  • @leppie, Sorry, I forgot mentioning XSLT :) Commented Jan 20, 2015 at 7:08

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

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?
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
Thanks for the answer. I'll try for that. Of course, this (stackoverflow.com/questions/11076920/…) seems to be the solution for that.
@Saurav, are you sure about it? I can see an extra comma getting aded at the end..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.