You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 4中JSON转XML实现方法咨询

在Angular 4中实现JSON转XML(适配你的WCF服务需求)

你已经有了XML转JSON的工具函数,那我们可以写一个对应的JSON转XML函数,完美适配你现有的数据结构(比如@开头的属性、#text文本节点、#cdataCDATA节点,还有数组形式的重复元素),刚好满足调用WCF服务的需求。

实现JSON转XML的核心函数

下面这个json2xml函数和你提供的xml2json逻辑一一对应,能把你用JSON构建的对象转换成符合WCF要求的XML字符串:

json2xml(json: any, rootName?: string): string {
  const X = {
    toXml: function(obj: any, nodeName: string, isRoot?: boolean): string {
      let xml = '';
      // 处理数组:生成重复的同名节点
      if (obj instanceof Array) {
        obj.forEach(item => {
          xml += X.toXml(item, nodeName);
        });
        return xml;
      }
      // 处理空值:生成自闭合节点
      if (obj == null) {
        return `<${nodeName}/>`;
      }
      // 处理基本类型(纯文本/数字)
      if (typeof obj !== 'object') {
        return `<${nodeName}>${X.escape(obj.toString())}</${nodeName}>`;
      }

      xml += `<${nodeName}`;
      const attributes: string[] = [];
      const children: string[] = [];
      let textContent = '';
      let cdataContent = '';

      // 遍历对象键值对,区分属性、文本、子元素
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          const value = obj[key];
          // 识别@开头的键为XML属性
          if (key.startsWith('@')) {
            const attrName = key.substring(1);
            attributes.push(`${attrName}="${X.escape(value.toString())}"`);
          }
          // 处理#text对应的普通文本节点
          else if (key === '#text') {
            textContent = X.escape(value.toString());
          }
          // 处理#cdata对应的CDATA块
          else if (key === '#cdata') {
            cdataContent = `<![CDATA[${value}]]>`;
          }
          // 其他键作为子元素处理
          else {
            children.push(X.toXml(value, key));
          }
        }
      }

      // 拼接属性到节点头部
      if (attributes.length > 0) {
        xml += ' ' + attributes.join(' ');
      }

      // 处理节点内容:区分空节点、纯文本/CDATA节点、带子元素的节点
      if (children.length === 0 && !textContent && !cdataContent) {
        xml += '/>';
      } else {
        xml += '>';
        xml += textContent;
        xml += cdataContent;
        xml += children.join('');
        xml += `</${nodeName}>`;
      }

      // 根节点添加XML声明
      if (isRoot) {
        xml = `<?xml version="1.0" encoding="UTF-8"?>${xml}`;
      }

      return xml;
    },
    // 转义XML特殊字符,避免格式错误
    escape: function(txt: string): string {
      return txt.replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&apos;');
    }
  };

  // 两种调用场景:指定根节点名,或直接传入带根节点的完整JSON对象
  if (rootName) {
    return X.toXml(json, rootName, true);
  } else {
    const rootKey = Object.keys(json)[0];
    return X.toXml(json[rootKey], rootKey, true);
  }
}

函数说明与使用示例

关键逻辑拆解

  • 属性映射:JSON中@xxx格式的键会被转换为XML节点的属性(如{ "@OrderId": "ORD-001" } → <OrderRequest OrderId="ORD-001">)
  • 文本/CDATA处理:#text对应普通文本内容,#cdata会生成CDATA块,适合包含特殊字符的内容
  • 数组处理:JSON数组会自动生成多个同名子节点,完美适配WCF中重复元素的要求
  • 特殊字符转义:自动处理XML敏感字符,确保生成的XML格式合法

实际使用示例

假设你构建了符合WCF参数要求的JSON对象:

const orderRequestJson = {
  "OrderRequest": {
    "@OrderId": "ORD-001",
    "Customer": {
      "Name": "John Doe",
      "Email": "john@example.com"
    },
    "Items": {
      "Item": [
        { "@ProductId": "PROD-1", "#text": "Laptop" },
        { "@ProductId": "PROD-2", "#cdata": "Wireless Mouse & Keyboard" }
      ]
    },
    "#text": "Sample Customer Order"
  }
};

调用函数生成XML字符串:

const xmlString = this.json2xml(orderRequestJson);

最终生成的XML结果:

<?xml version="1.0" encoding="UTF-8"?>
<OrderRequest OrderId="ORD-001">
  Sample Customer Order
  <Customer>
    <Name>John Doe</Name>
    <Email>john@example.com</Email>
  </Customer>
  <Items>
    <Item ProductId="PROD-1">Laptop</Item>
    <Item ProductId="PROD-2"><![CDATA[Wireless Mouse & Keyboard]]></Item>
  </Items>
</OrderRequest>

转换为XML DOM对象(可选)

如果需要生成XML DOM对象而非字符串,可以使用浏览器原生的DOMParser:

const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, 'application/xml');

Angular 4中的使用建议

你可以把这个json2xml函数封装到一个Angular服务(比如XmlJsonConversionService)中,通过依赖注入的方式在各个组件中调用,符合Angular的模块化开发规范。


内容的提问来源于stack exchange,提问作者Barr J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:45:50