0

I have some XML in this format

<items>
    <item>
    <float>0.75</float>
    <string>NAME</string>
    <string>Bob</string>
    <string>CREATION_TIME</string>
    <timestamp>2012-11-01 00:03:08</timestamp>
    <string>OCCUPATION</string>
    <null />
    </item>
</items>

I'd like to transform it to a format like this

<item>
    <NAME>Bob</NAME>
    <CREATION_TIME>2012-11-01 00:03:08</CREATION_TIME>
    <OCCUPATION></OCCUPATION>
</item>

Is it possible to do it through plain XSLT transforms or would I have to write my own parser?

1
  • Can you explain which child elements of item elements you want to process and which ones you want to relate? Why is the float ignored, which elements should be paired to create a <some-name>some value</some-name> result element? Commented Jun 20, 2013 at 17:05

1 Answer 1

2
<xsl:template match="item">
  <xsl:copy>
    <xsl:apply-templates select="string[position() mod 2 = 1]"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="string">
  <xsl:element name="{.}">
    <xsl:value-of select="following-sibling::*[1]"/>
  </xsl:element>
</xsl:template>
Sign up to request clarification or add additional context in comments.

4 Comments

+1 - one quick item: your solution completely removes the <OCCUPATION> element, whereas the OP's expected solution retains it.
@ABach, you are right, I am currently not sure what determines which elements to process and relate. I will ask the poster.
@MartinHonnen If you number all the strings, the odd ones are the keys and the even ones are the values.
@Narabhut, the <xsl:apply-templates select="string[position() mod 2 = 1]"/> takes the odd string elements but that way the <string>OCCUPATION</string> is not treated as a key (as it is the 4th string). Is that what you want?

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.