匯入 XML 檔案
Bun 原生支援 .xml 匯入
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>
像匯入其他原始檔一樣匯入該檔案。模組就是解析後的文件:根元素對應一個鍵,屬性對應 "@name" 鍵,重複的元素則對應陣列。每個值都是字串。
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"]
根元素也可以作為命名匯入使用:
import { config } from "./config.xml";
console.log(config.database["@name"]); // => "myapp"
console.log(Number(config.server["@timeout"])); // => 30
如需在執行環境解析 XML 字串,請使用 Bun.XML.parse():
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"
請參閱 XML,瞭解 Bun 對 XML 的其餘支援,包括有序的 { compact: false } 節點樹和 Bun.XML.stringify()。