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

Delphi XML Data Binding Interfaces生成列表项XML结构不符合预期求助

Delphi XML数据绑定生成XML结构错误问题解决

问题描述

使用Delphi的「XML Data Binding Interfaces」从XSD文件生成XML时,列表场景下生成的结构不符合预期。具体代码如下:

...

implementation

var
  inv: IXMLInvoiceWood;
const
  XMLFile = '../../../TestInvoiceFile.xml';

{$R *.dfm}

procedure setReference(const pmcInv: IXMLInvoiceWood; const pmcAssignedBy, pmcRefName: string);
var
  Ref: IXMLInvoiceReference;
begin
  ref := pmcInv.InvoiceWoodHeader.InvoiceReference.Add;
  ref.SetAttributeNS('AssignedBy','',pmcAssignedBy);
  ref.SetAttributeNS('InvoiceReferenceType','',pmcRefName);
  ref.Attributes[pmcRefName] := 87532;
end;

procedure TForm2.btn1Click(Sender: TObject);
begin
  if inv = nil then
  inv := NewInvoiceWood;
  begin
    inv.OwnerDocument.Encoding := 'utf-8';
    inv.OwnerDocument.Options := inv.OwnerDocument.Options - [doAttrNull] + [doAutoSave] + [doNodeAutoIndent] + [doNodeAutoCreate];
    inv.InvoiceType := 'Invoice';
    inv.InvoiceWoodHeader.InvoiceNumber := '123456789';
    SetReference(Inv, 'seller', 'LoadingOrderNo');
    Inv.OwnerDocument.SaveToFile(XMLFile);

    mmo1.Lines.LoadFromFile(XMLFile);
  end;

当前生成的XML输出

<?xml version="1.0" encoding="utf-8"?>
<InvoiceWood InvoiceType="Invoice">
  <InvoiceWoodHeader>
    <InvoiceNumber>123456789</InvoiceNumber>
    <InvoiceReference AssignedBy="seller" InvoiceReferenceType="LoadingOrderNo" LoadingOrderNo="87532"/>
  </InvoiceWoodHeader>
</InvoiceWood>

期望的XML结构

<?xml version="1.0" encoding="utf-8"?>
<InvoiceWood InvoiceType="Invoice">
  <InvoiceWoodHeader>
    <InvoiceNumber>123456789</InvoiceNumber>
    <InvoiceReference AssignedBy="Seller" InvoiceReferenceType="LoadingOrderNo">87532</InvoiceReference>
  </InvoiceWoodHeader>
</InvoiceWood>

错误原因与解决方法

核心错误是把数值87532设置成了<InvoiceReference>节点的属性,而实际上需要将其作为节点的文本内容。另外注意AssignedBy的值大小写,当前是seller,期望是Seller,需要同步调整。

  1. 修改setReference过程的最后一行:
    将
ref.Attributes[pmcRefName] := 87532;

替换为

ref.Text := '87532';
  1. 调用SetReference时调整第二个参数的大小写:
SetReference(Inv, 'Seller', 'LoadingOrderNo');

修改后的setReference过程如下:

procedure setReference(const pmcInv: IXMLInvoiceWood; const pmcAssignedBy, pmcRefName: string);
var
  Ref: IXMLInvoiceReference;
begin
  ref := pmcInv.InvoiceWoodHeader.InvoiceReference.Add;
  ref.SetAttributeNS('AssignedBy','',pmcAssignedBy);
  ref.SetAttributeNS('InvoiceReferenceType','',pmcRefName);
  ref.Text := '87532';
end;

调整后生成的XML就会符合预期结构,数值会作为<InvoiceReference>节点的文本内容,而非额外属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 00:37:40