【教程】将 XML 内容转换为 JSON 格式

【声明】此代码仅是参考示例,实际可能根据实际的数据格式进行额外的处理。因为 XML 没有类型信息,所以这里生成JSON全为字符串类型。

procedure Xml2Json(AParent: TQXML; AJson: TQJson; AEncodeAttrs: Boolean);
var
  I, J: Integer;
  AChildXml: TQXML;
  Attr: TQXMLAttr;
  AChildJson: TQJson;
  function IsTextNode(ANode:TQXML):Boolean;
  var
    I:Integer;
  begin
    Result:=true;
    if ANode.NodeType=xntNode then
    begin
      for I := 0 to ANode.Count-1 do
      begin
        if ANode[I].NodeType=xntNode then
          Exit(False);
      end;
    end;
  end;
begin
  for I := 0 to AParent.Count - 1 do
  begin
    AChildXml := AParent[I];
    AChildJson := AJson.Add(AChildXml.Name);
    if not IsTextNode(AChildXml) then
    begin
      Xml2Json(AChildXml, AChildJson, AEncodeAttrs);
      if AEncodeAttrs then
      begin
        for J := 0 to AChildXml.Attrs.Count - 1 do
        begin
          Attr := AChildXml.Attrs[J];
          AChildJson.Add(Attr.Name).AsString := Attr.AsString;
        end;
      end;
    end
    else
      AChildJson.AsString := AChildXml.Text;
  end;
end;

【示例】

procedure TForm2.Button1Click(Sender: TObject);
var
  AXml: TQXML;
  AJson: TQJson;
begin
  AXml := TQXML.Create;
  with AXml.Add('root') do
  begin
    Add('item1').Text := '1000';
    Add('item2').AddText('this is text');
    Attrs.Add('attr1').AsString := 'idm';
  end;
  AJson := AcquireJson;
  Xml2Json(AXml, AJson, true);
  Memo1.Text := AJson.AsJson;
  ReleaseJson(AJson);
  FreeAndNil(AXml);
end;

生成JSON效果如下:

{
  "root":{
    "item1":"1000",
    "item2":"this is text",
    "attr1":"idm"
  }
}
滚动至顶部