【问题标题】:Is there any xml serializer like golang有没有像golang这样的xml序列化器
【发布时间】:2021-08-19 01:52:54
【问题描述】:

我使用 XML 作为配置文件,并希望将文件反序列化为记录 像这样:

TAddress = record
    City, State :string; 
end;
TAccount = record
    ID: string;
end;
type Accounts = record
    ID:  string;
    Account: array of TAccount;
end;
type Person = record
    Address:    TAddress;
    AccountsID: int ;
    Accounts:   Accounts;
end;

还有这样的 XML:

<person AccountsID="1">
    <Address City="aa" State="bb"></Address>
    <Accounts ID="dd">
        <Account>
            <ID>a1</ID>
        </Account>
        <Account>
            <ID>a2</ID>
        </Account>
        <Account>
            <ID>a3</ID>
        </Account>
    </Accounts>
</person>

在golang中,通过标签将字段控制为属性或子节点很简单:

type Address struct {
    City, State string `xml:",attr"`
}
type Account struct {
    ID string `xml:",attr"`
}
type Accounts struct {
    ID      string `xml:",attr"`
    Account []Account
}
type Person struct {
    XMLName    xml.Name `xml:"person"`
    Address    Address
    AccountsID int `xml:"AccountsID,attr"`
    Accounts   Accounts
}

我读了:What's a good way to serialize Delphi object tree to XML--using RTTI and not custom code?

TJvAppXMLFileStorage 这么大,我就不测试了

OmniXML 和 NativeXml 只支持类而不支持记录,它把所有字段都解析为子字段。为什么我使用记录:我不想在每个类中释放对象

superobject superobjectxml可以通过修改代码来使用,但是bug太多了。

除了自己写轮子还有什么好办法吗?

【问题讨论】:

标签: xml delphi


【解决方案1】:

kbmMW 的 XML marshaller/unmarshaller 支持记录和对象,因此它应该能够处理您的情况。

您可以试用免费的 kbmMW 社区版

示例元素与属性:

[kbmMW_Root('address',[mwrfIncludeOnlyTagged])]
TMyAddress = class
public
   [kbmMW_Attribute('address1')]
   MyAddress1:string;

   [kbmMW_Attribute('address2')]
   MyAddress2:string;

   [kbmMW_Element('zipcode')]
   MyZip:string;

   constructor Create(AAddress1,AAddress2,AZip:string);
end;

【讨论】:

  • 主要问题是如何控制一个字段作为属性还是作为子节点
  • 已编辑回复。见上文。
  • 本例使用的是TClass,但使用记录的方式相同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-22
  • 2016-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
相关资源
最近更新 更多