租房小程序前端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

37 lines
1.1 KiB

3 months ago
  1. import { formatObjKey } from './formatObjKey';
  2. function type(params) {
  3. return Object.prototype.toString
  4. .call(params)
  5. .replace(/(.*? |])/g, '')
  6. .toLowerCase();
  7. }
  8. export function obj2xml(obj, options?) {
  9. let s = '';
  10. if (options && options.headers) {
  11. s = '<?xml version="1.0" encoding="UTF-8"?>\n';
  12. }
  13. if (options && options.firstUpperCase) {
  14. obj = formatObjKey(obj, 'firstUpperCase');
  15. }
  16. if (type(obj) === 'object') {
  17. Object.keys(obj).forEach(key => {
  18. // filter undefined or null
  19. if (type(obj[key]) !== 'undefined' && type(obj[key]) !== 'null') {
  20. if (type(obj[key]) === 'string' || type(obj[key]) === 'number') {
  21. s += `<${key}>${obj[key]}</${key}>`;
  22. } else if (type(obj[key]) === 'object') {
  23. s += `<${key}>${obj2xml(obj[key])}</${key}>`;
  24. } else if (type(obj[key]) === 'array') {
  25. s += obj[key].map(keyChild => `<${key}>${obj2xml(keyChild)}</${key}>`).join('');
  26. } else {
  27. s += `<${key}>${obj[key].toString()}</${key}>`;
  28. }
  29. }
  30. });
  31. } else {
  32. s += obj.toString();
  33. }
  34. return s;
  35. }