The value returned by the ‘xslt_select_xml’ shortcode can be formatted as JSON, rather than XML, by adding the attribute ‘format=”json”‘.
shortcode
The values returned by [xslt_select_xml/]
can be formatted as JSON, rather than XML, by adding the attribute format="json"
.
[xslt_select_xml xml="sample.xml" format="json" /]
format=”json”
{"RESULT":[{"attributes":{"xml":"\/srv\/plugins.tenandtwo.com\/htdocs\/wp-content\/plugins\/tenandtwo-xslt-processor\/xsl\/sample.xml","select":"\/"},"sample":[{"comment":[{"cdata":"This is a test XML file. It contains this <comment> node, followed by a <list> node containing several <item> nodes, and a <dates> node containing several <date> nodes."}],"list":[{"attributes":{"title":"My List"},"item":[{"attributes":{"value":"1"},"cdata":"One"},{"attributes":{"value":"2"},"cdata":"Two"},{"attributes":{"value":"3"},"cdata":"Three"},{"attributes":{"value":"4"},"cdata":"Four"}]}],"dates":[{"date":[{"cdata":"2022-12-02 12:12:12"},{"cdata":"2023-03-03 13:13:13"}]}]}]}]}
format=”xml”
<RESULT xml="/srv/plugins.tenandtwo.com/htdocs/wp-content/plugins/tenandtwo-xslt-processor/xsl/sample.xml" select="/"> <sample> <comment>This is a test XML file. It contains this <comment> node, followed by a <list> node containing several <item> nodes, and a <dates> node containing several <date> nodes.</comment> <list title="My List"> <item value="1">One</item> <item value="2">Two</item> <item value="3">Three</item> <item value="4">Four</item> </list> <dates> <date>2022-12-02 12:12:12</date> <date>2023-03-03 13:13:13</date> </dates> </sample> </RESULT>
javascript
To bring the data into page scope, we can use a “Custom HTML” block to insert Javascript into the page.
Here, we’re sending the result of JSON.parse()
to the browser’s console for debugging, and immediately writing some object values to the page. More realistically, $mydata
would be accessed and used later, perhaps within an onload()
or onchange()
callback method.
<script language="javascript">
var $mydata = JSON.parse('[xslt_select_xml xml="sample.xml" format="json" /]');
console.log($mydata);
document.write('<pre>');
document.write('\n xml = ' + $mydata.RESULT[0].attributes.xml);
document.write('\n select = ' + $mydata.RESULT[0].attributes.select);
document.write('</pre>');
</script>