On this page
article
Fast XML Parser
Example code
Example code to handle conveting JSON to XML.
This example uses Astro using fast-xml-parser. Notice that XML needs a root document (JSON doesn’t). I also have to send it as a JSON object. Directly sending like ‘123456’ will cause it to try and encode that. So just send a JSON object with a single root and I should be fine.
import { XMLBuilder } from "fast-xml-parser";
import type { APIRoute } from 'astro';
export const GET: APIRoute = async (context) => {
const data = await getData()
const builder = new XMLBuilder()
const xmlContent = builder.build({
root: {
data1: data.dataOne,
data2: data.dataTwo,
}
})
const validXML = XMLValidator.validate(xmlContent)
if(validXML) {
return new Response(xmlContent)
} else {
return new Response("Invalid XML!")
}
}