Plugin Example for Converting XML to JSON

Hi fellow Hitchhikers,

As of the writing of this post, our Connector framework does not natively support ingesting content in XML format. That being said, pulling data from an XML source is possible today with the use of a function source.

Below is an example of a basic plugin that can be used as a function source to retrieve content from an XML source and convert the content to JSON format that the platform can ingest. The code for this plugin can also be found on GitHub here.

A Yext plugin is made up of two files: a mod.ts file and a _resource.json file. In the latter file, we define the schema:

// _resource.json

{
    "$id": "XmlToJson",
    "$schema": "https://schema.yext.com/config/platform/plugin/v1"
}

In the mod.ts file, we write our function:

// mod.ts

import { xml2js } from "https://deno.land/x/xml2js@1.0.0/mod.ts";

const myHeaders = new Headers();
// add authentication header if necessary
const requestOptions = {
    method: 'GET',
    headers: myHeaders,
};


export const xmlConverter = async (inputString: string) => {
    const xmlEndpoint = "XML_ENDPOINT";

    // fetch XML data and convert to json
    const xmlContent = await fetch(xmlEndpoint, requestOptions).then(response => response.text());
    const jsonContent = xml2js(xmlContent, {compact: true});
    
    // select and manipulate JSON as needed and return final data to platform
    const response = { data: jsonContent }
    return JSON.stringify(response);
}

Simply update the placeholder with the endpoint you’re retrieving the XML from and add an authentication header if necessary. You may also want to select just a subset of the data in the jsonContent to return to the platform in the response object.

Once the plugin is ready to go, you can use the Yext CLI to add the resource to your Yext account. After logging into your account via the CLI, navigate into the plugin’s folder in your command line and run the following command:

yext resources apply .

Note: Running this command with the “.” at the end should only be done if you are running the command from within a dedicated folder for the plugin that is comprised only of the two files mentioned above. If you are running the command from a different directory, specify the path to the plugin folder as part of the command. For example:

yext resources apply documents/plugins/pluginFolder

Now that the plugin exists in your account, you can create a Connector using the new plugin as the source!

Hope this proves useful,
DJ

1 Like

Hi, this i usefull indeed. Thank you. :+1:t2:

Hi @DJ_Corbett!

Thanks for sharing this! Just to confirm - would this same plugin be usable if the data source were an SFTP/XML file pickup, as opposed to an API source for the Connector?