gpt4 book ai didi

c# - XML 序列化嵌套

转载 作者:太空宇宙 更新时间:2023-11-03 23:40:34 25 4
gpt4 key购买 nike

我正在做一些 XML 序列化并尝试像这样获得输出:

<Claim>
<Source>...</Source>
<Vehicle>...</Vehicle>
<ThirdParty>...</ThirdParty>
<ThirdParty>...</ThirdParty>
<ThirdParty>...</ThirdParty>
</Claim>

但是我的输出是:

  <Claim>
<Source>...</Source>
<Vehicle>...</Vehicle>
<ThirdParty>
<ThirdParty>...</ThirdParty>
<ThirdParty>...</ThirdParty>
<ThirdParty>...</ThirdParty>
</ThirdParty>
</Claim>

第三方嵌套在列表中而不是声明中,我如何才能在 XML 的基础上获取第三方而不是在另一个第三方节点中。我希望这是有道理的。

我要序列化的对象:

    public class ThirdParty
{
public ThirdPartyDetails Details { get; set; }
public ThirdPartyVehicle Vehicle { get; set; }
public ThirdPartyPolicy Policy { get; set; }
public ThirdPartyPrincipleCompany PrincipleCompany { get; set; }
}


public class Claim
{
public List<ThirdParty> ThirdParty { get; set; }
}

初始化

ThirdParty ThirdParty1 = new ThirdParty{ Details = ThirdPartyDetails, Policy=ThirdPartyPolicy, PrincipleCompany=ThirdPartyPrinciple, Vehicle=ThirdPartyVehicle};

ThirdParty ThirdParty2 = new ThirdParty{ Details = ThirdPartyDetails, Policy=ThirdPartyPolicy, PrincipleCompany=ThirdPartyPrinciple, Vehicle=ThirdPartyVehicle};

List<ThirdParty> LP = new List<ThirdParty>();

LP.Add(ThirdParty1);
LP.Add(ThirdParty2);


Claim Claim = new Claim { ThirdParty = LP };

序列化

  var subReq = Claim;
using (StringWriter sww = new Utf8StringWriter())
{
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = false,
Encoding = Encoding.Unicode
};

using (XmlWriter writer = XmlWriter.Create(sww, xmlWriterSettings))
{
xsSubmit.Serialize(writer, subReq);
var xml = sww.ToString();
PrintOutput(xml);

Console.WriteLine(xml);
}
}

编辑:回复彼得:

Okay, now I'm having a problem with the output, I'm not using it correctly I think. So because I'm inheriting the properties of List I can then use the Add method of List: claim.Add(ThirdParty1); claim.Add(ThirdParty2); Now my output is ... ... It's completely Ignored Source and Vehicle. Any ideas?

最佳答案

您已声明 Claim 有一个 ThirdParty 的集合,但您希望它被序列化为 Claim 是一个 ThirdParty 的集合。

要获得 Claim 是一个 ThirdParty 集合的场景,从 List<ThirdParty> 派生 Claim并添加所需的属性和方法。

此示例假设您有另一个类 Vehicle。

public class Claim : List<ThirdParty> {
public string Source { get; set; }
public Vehicle Vehicle { get; set; }
}

Claim 是 ThirdParty 的列表,但还有其他属性和潜在的其他方法。

然而

那是行不通的。如果您这样做,它会停止序列化所有其他属性,您得到的只是集合的子项。

所以坚持组合,但用 [XmlElement] 标记它属性,像这样:

public class Claim 
{
public Source Source { get; set; }
public Driver Driver { get; set; }
public Owner Owner { get; set; }
public Vehicle Vehicle { get; set; }
public Accident Accident { get; set; }
public Policy Policy { get; set; }
public Insurer Insurer { get; set; }
public Solicitor Solicitor { get; set; }
[XmlElement]
public List<ThirdParty> ThirdParty { get; set; }
}

关于c# - XML 序列化嵌套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29143382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com