
function objectToXml(obj, rootName) {
let xml = '';
// 添加 XML 声明
xml += '<?xml version="1.0" encoding="UTF-8"?>';
// 添加根元素标签
xml += `<${rootName}>`;
// 遍历对象属性,添加元素标签和属性
for (const property in obj) {
if (obj.hasOwnProperty(property)) {
xml += '<' + property + '>';
if (typeof obj[property] === 'object') {
xml += objectToXml(new Object(obj[property]));
} else {
xml += obj[property];
}
xml += '</' + property + '>';
}
}
// 添加根元素闭合标签
xml += `</${rootName}>`;
return xml;
}
const obj = {
name: 'John',
age: 30,
dateOfBirth: {
year: 1990,
month: 3,
day: 15
}
};
const xml = objectToXml(obj, 'person');
console.log(xml);
输出结果:
<?xml version="1.0" encoding="UTF-8"?>
<person>
<name>John</name>
<age>30</age>
<dateOfBirth>
<year>1990</year>
<month>3</month>
<day>15</day>
</dateOfBirth>
</person>
js如何利用js2xmlparser工具将对象转为xml文件
上面是“js如何将对象手动拼接为xml文件”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。
当前网址:https://m.ipkd.cn/webs_4143.html
声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

一款来自杭州的全球领先的医疗大模型——WiseDiag
MySQL如何利用数据库视图进行多租户隔离