Cloud Learner
Cloud Learner

Reputation: 141

How to print all the keys in xml dictionary value

I've this xml

<namedAnchor>
  {'Beacon': 'ORG', 'One': 'CARDINAL', 'Meadows': 'ORG', 'Congress': 'ORG', 'end of the month': 'DATE', 'second': 'ORDINAL', 'Tuesday': 'DATE', 'Wednesday': 'DATE', 'third': 'ORDINAL', 'New Yorker': 'NORP', 'Scramble for Medical Equipment Johnson City': 'ORG', 'US': 'GPE'}
</namedAnchor>

I need to print all the keys in comma separated in page and I've tried this.

<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<body>
<xsl:for-each select="tokenize(namedAnchor, ':')">
  <p><xsl:value-of select="." /></p>
</xsl:for-each>
</body>
</html>

What i want is Beacon, One, Meadows Can someone provide answer for my question.>

Upvotes: 0

Views: 316

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 116992

The tokenize() function requires XSLT 2.0. libxslt is an XSLT 1.0 processor. However, libxslt does support the EXSLT str:split() extension function, so you could do:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:str="http://exslt.org/strings"
extension-element-prefixes="str">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/">
    <output>
        <xsl:for-each select="str:split(normalize-space(namedAnchor), ', ')" >
            <item>
                <xsl:value-of select='translate(substring-before(., ":"), "{}&apos;", "")'/>
            </item>
        </xsl:for-each>
    </output>
</xsl:template>

</xsl:stylesheet>

to get:

<?xml version="1.0" encoding="UTF-8"?>
<output>
  <item>Beacon</item>
  <item>One</item>
  <item>Meadows</item>
  <item>Congress</item>
  <item>end of the month</item>
  <item>second</item>
  <item>Tuesday</item>
  <item>Wednesday</item>
  <item>third</item>
  <item>New Yorker</item>
  <item>Scramble for Medical Equipment Johnson City</item>
  <item>US</item>
</output>

Note that this assumes none of the keys contains the pattern ", " (which technically they could, since they are enclosed in quotes). To properly parse the contents, you would need an XSLT 3.0 processor that can process JSON.

Upvotes: 1

Related Questions