js如何将对象手动拼接为xml文件

543 ℃
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文件

标签: xml文件, 对象转换

上面是“js如何将对象手动拼接为xml文件”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。

当前网址:https://m.ipkd.cn/webs_4143.html

声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

新站做网站排名优化需要注意哪些细节
帝国cms常见问题有哪些
Vue中如何在子组件中验证props
帝国cms7.2版本phome_enewstags数据表字段解释(TAGS表
js数组根据每行字数进行排序,并前面加序号(中文内容)