下面给你一个可直接上线使用的「XML 在线格式化工具」,支持 格式化 / 压缩 / 校验错误,适合放在 工具站 / 博客 / WordPress 前台页面。
🧾 XML 在线格式化
XML Pretty / Minify / 校验工具
✅ 功能说明
- ✔ XML 一键美化(缩进、换行)
- ✔ XML 压缩成一行
- ✔ XML 语法校验(错误提示)
- ✔ 纯前端实现,数据不上传服务器
- ✔ 支持大文本、复制即用
🌐 使用场景
- 接口返回 XML 调试
- WebService / SOAP 排错
- 配置文件检查
- 学习 XML 结构
💡 完整可用代码(HTML + CSS + JS)
保存为
xml-formatter.html即可使用
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>XML在線格式化 | XML Pretty / 校驗工具</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
background: #0f172a;
color: #e5e7eb;
font-family: system-ui, -apple-system;
padding: 20px;
}
.container {
max-width: 900px;
margin: auto;
}
h1 {
text-align: center;
margin-bottom: 20px;
}
textarea {
width: 100%;
height: 260px;
padding: 15px;
border-radius: 12px;
border: none;
font-size: 14px;
background: #020617;
color: #38bdf8;
font-family: Consolas, monospace;
}
.buttons {
display: flex;
gap: 12px;
margin: 15px 0;
}
button {
flex: 1;
padding: 12px;
border: none;
border-radius: 10px;
font-size: 15px;
cursor: pointer;
background: linear-gradient(135deg,#6366f1,#3b82f6);
color: #fff;
}
.result {
margin-top: 10px;
font-size: 14px;
color: #22c55e;
}
.error {
color: #ef4444;
}
</style>
</head>
<body>
<div class="container">
<h1>🧾 XML 在線格式化工具</h1>
<textarea id="xmlInput" placeholder="請貼上 XML 內容..."></textarea>
<div class="buttons">
<button onclick="formatXML()">格式化</button>
<button onclick="minifyXML()">壓縮</button>
<button onclick="validateXML()">校驗</button>
</div>
<div id="msg" class="result"></div>
</div>
<script>
function parseXML(xml) {
const parser = new DOMParser();
const doc = parser.parseFromString(xml, "application/xml");
const err = doc.getElementsByTagName("parsererror");
if (err.length) throw new Error(err[0].textContent);
return doc;
}
function formatXML() {
try {
const xml = document.getElementById("xmlInput").value;
const doc = parseXML(xml);
const serializer = new XMLSerializer();
let formatted = serializer.serializeToString(doc);
formatted = formatted.replace(/></g, ">\n<");
document.getElementById("xmlInput").value = formatted;
showMsg("✅ XML 格式化完成");
} catch (e) {
showError(e.message);
}
}
function minifyXML() {
try {
const xml = document.getElementById("xmlInput").value;
parseXML(xml);
const minified = xml.replace(/\s+/g, " ").trim();
document.getElementById("xmlInput").value = minified;
showMsg("✅ XML 已壓縮");
} catch (e) {
showError(e.message);
}
}
function validateXML() {
try {
parseXML(document.getElementById("xmlInput").value);
showMsg("✅ XML 語法正確");
} catch (e) {
showError("❌ XML 錯誤:" + e.message);
}
}
function showMsg(msg) {
const el = document.getElementById("msg");
el.className = "result";
el.innerText = msg;
}
function showError(msg) {
const el = document.getElementById("msg");
el.className = "result error";
el.innerText = msg;
}
</script>
</body>
</html>