Comma-delimited string to XML

polly
User offline. Last seen 2 years 7 weeks ago. Offline
Joined: 02/12/2009
Points: 150

 Does anyone know how to convert a comma-delimited string to XML?

I saw a post on the last step - the actual conversion, but I'm looking for the iteration mechanism too I guess.

The example:

foo1,foo2,foo3

Desired result:

<xml><item>foo1<item><item>foo2<item><item>foo3<item></xml>

Any help from the Community is appreciated.

0
Your rating: None
Karthic Thope
Karthic Thope's picture
User offline. Last seen 8 weeks 1 day ago. Offline
Joined: 09/22/2008
Points: 61

tokenize function will help you do that, here is an example.

 

<mashup xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.jackbe.com/2008-03-01/EMMLSchema ../src/schemas/EMMLSpec.xsd"
        xmlns="http://www.jackbe.com/2008-03-01/EMMLSchema"
        name="string2XML">
    <operation name="convert">
        <input name="records" type="string" default="foo1,foo2,foo3"/>
        <output name="result" type="document">
                <items/>
        </output>
          <foreach variable="token" items="tokenize($records, ',')">
                <annotate variable="result" expr=".">
                        element item {$token}
                </annotate>
          </foreach>
    </operation>
</mashup>

polly
User offline. Last seen 2 years 7 weeks ago. Offline
Joined: 02/12/2009
Points: 150

This is a great example.  Thank you very much.

I'm stuck on another item.  The processing I'm doing in the above foreach is to call another mashup I wrote.  That works fine, it brings back the result, which is something like <xml> <item>foo1</item> ( yes, a single item ).  

So after some looping of foreach, I may have 3 of these item nodes appended.

Problem is the way I'm doing it now, I have a parent node being created after each loop, so it's like:

<newitem><item>foo1</item></newitem><newitem><item>foo2</item></newitem><newitem><item>foo3</item></newitem>

Is there a way to strip the outer node from each result?

If I just put the $result in the append, without an element node, it does not run.

Sorry if this is confusing. Thanks in advance.

smitchell
smitchell's picture
User offline. Last seen 15 hours 43 min ago. Offline
Joined: 08/29/2008
Points: 34

What you can do is to put the wrapping document node in the variable before you call <appendresult>. Something like this: 

<variable name="myitems type="document>
<newitems/>
</variable>

<foreach ....>
...
  <appendresult outputvariable="myitems">
    <item>{$tokenize-result}</item>
  </appendresult>
...
</foreach>

You should get:

<newitems>
  <item>foo1</item>
  <item>bar2</item>
  ...
</newitems>

 

Sara, technical writer/jackbe