Runtime
Bundler
Package Manager
Test Runner
Guides
Reference
Blog
Install Bun
Guides Module System

Import an XML file

Bun natively supports .xml imports.

config.xml
<?xml version="1.0" encoding="UTF-8"?>
<config env="production">
  <database host="localhost" port="5432" name="myapp"/>
  <server port="3000" timeout="30"/>
  <feature name="auth"/>
  <feature name="rateLimit"/>
</config>

Import the file like any other source file. The module is the parsed document: one key for the root element, "@name" keys for attributes, arrays for repeated elements, and every value a string.

config.ts
import doc from "./config.xml";

doc.config["@env"]; // => "production"
doc.config.database["@host"]; // => "localhost"
doc.config.server["@port"]; // => "3000"
doc.config.feature.map(f => f["@name"]); // => ["auth", "rateLimit"]

The root element is also available as a named import:

config.ts
import { config } from "./config.xml";

console.log(config.database["@name"]); // => "myapp"
console.log(Number(config.server["@timeout"])); // => 30

For parsing XML strings at runtime, use Bun.XML.parse():

config.ts
const data = Bun.XML.parse(`
  <user id="7">
    <name>John Doe</name>
    <hobby>reading</hobby>
    <hobby>coding</hobby>
  </user>
`);

console.log(data.user.name); // => "John Doe"
console.log(data.user.hobby); // => ["reading", "coding"]
console.log(data.user["@id"]); // => "7"

See XML for the rest of Bun's XML support, including the ordered { compact: false } node tree and Bun.XML.stringify().

On this page

No Headings