【工具】XML和JSON互相转换

1、JSON解析为XML

function parseJSONToXML(json) {
  let xmlDoc = document.implementation.createDocument(null, '');

  function parseValue(value, parentElement) {
    if (Array.isArray(value)) {
      for (let item of value) {
        let arrayElement = xmlDoc.createElement(parentElement.tagName);
        parseValue(item, arrayElement);
        if (parentElement) {
          parentElement.appendChild(arrayElement);
        }
      }
    } else if (typeof value === 'object') {
      parseObject(value, parentElement);
    } else {
      parentElement.textContent = value;
    }
  }

  function parseObject(obj, parentElement) {
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        let value = obj[key];
        let element = xmlDoc.createElement(key);

        parseValue(value, element);

        if (parentElement) {
          parentElement.appendChild(element);
        } else {
          xmlDoc.appendChild(element);
        }
      }
    }
  }

  parseObject(json, null);

  let serializer = new XMLSerializer();
  return '' + serializer.serializeToString(xmlDoc);
}

// 使用示例
let json = {
  root: {
    name: 'John',
    age: 30,
    addresses: [
      { street: 'Main St', city: 'City1' },
      { street: 'Second St', city: 'City2' }
    ]
  }
};

let xmlString = parseJSONToXML(json);
console.log(xmlString);

2、XML解析为JSON

function parseXMLToJSON(xml) {
  let parser = new DOMParser();
  let xmlDoc = parser.parseFromString(xml, 'text/xml');

  function parseElement(element) {
    let obj = {};
    if (element.hasChildNodes()) {
      let nestedElements = Array.from(element.children);
      if (nestedElements.length > 0) {
        nestedElements.forEach((nestedElement) => {
          let key = nestedElement.tagName;
          let value = parseElement(nestedElement);
          if (obj.hasOwnProperty(key)) {
            if (!Array.isArray(obj[key])) {
              obj[key] = [obj[key]];
            }
            obj[key].push(value);
          } else {
            obj[key] = value;
          }
        });
      } else {
        obj = element.textContent;
      }
    }
    return obj;
  }

  let rootNode = xmlDoc.documentElement;
  let json = {};
  let rootElement = parseElement(rootNode);
  json[rootNode.tagName] = rootElement;

  return JSON.stringify(json);
}

// 使用示例
let xmlString = 'John30Main StCity1Second StCity2';

let json = parseXMLToJSON(xmlString);
console.log(json);

你可能感兴趣的:(总结,xml,json,javascript)