Recently I was working on a project that required me to send an HTTPRequest, however, the API returned an XML instead of the now commonly used JSON. Because Roblox doesn’t (yet) have a built in XML parser, I decided to look for APIs, but I could only find one that is actually working, but it is limited, and I don’t want to pay for it just for others to use it. Because of this, I made an XML parser module.
Setup:
- Get the module from here.
- Place it into any script that needs to parse XML, or anywhere which can be accessible from such script.
Usage:
- In your script, require the module
local xmlParser = require(script.XMLParser)
- Call the function and assign it to a variable
local parsedXML = xmlParser.parseXML(xml)
Example:
local xml =
[[
<store>
<fruit>
<name>Apple</name>
<color>Red</color>
<variety>
<type>Fuji</type>
<origin>Japan</origin>
</variety>
<variety>
<type>Granny Smith</type>
<origin>Australia</origin>
</variety>
</fruit>
<fruit>
<name>Banana</name>
<color>Yellow</color>
</fruit>
</store>
]]
local xmlParser = require(script.XMLParser)
local parsedXML = xmlParser.parseXML(xml)
print(parsedXML)
Output:
{
["store"] = {
["fruit"] = {
[1] = {
["color"] = "Red",
["name"] = "Apple",
["variety"] = {
[1] = {
["origin"] = "Japan",
["type"] = "Fuji"
},
[2] = {
["origin"] = "Australia",
["type"] = "Granny Smith"
}
}
},
[2] = {
["color"] = "Yellow",
["name"] = "Banana"
}
}
}
}
Some notes:
- All tags are in alphabetical order (but this doesn’t affect retrieving data from the array
- In case of multiple tags with the same name, they get merged under one tag, but with a separate table for each original tag
- Content that is not a tag but formatted similarly to XML (e. g. HTML, RichText) might be added to the array as a new tag (and there is not really a workaround, but if you know any, please tell me)
- To retrieve data, simply do
local fruits = parsedXML.store.fruit