gpt4 book ai didi

c# - 当它们不是 "shaped"时将 XML 反序列化为对象?

转载 作者:行者123 更新时间:2023-11-30 21:56:16 30 4
gpt4 key购买 nike

我有一个像这样的 XML 片段:

<coverageCd>WEL
<descriptorCd>SMIO
<descriptorCdStartDate>01/01/2015</descriptorCdStartDate>
<descriptorCdEndDate>12/31/9999</descriptorCdEndDate>
</descriptorCd>
<descriptorCd>AAE
<descriptorCdStartDate>01/01/2015</descriptorCdStartDate>
<descriptorCdEndDate>12/31/9999</descriptorCdEndDate>
</descriptorCd>
</coverageCd>

我需要自动将其转换为以下类结构:

public class XmlCoverageCode
{
public string CoverageCode { get; set; }
public IEnumerable<XmlDescriptor> Descriptors { get; set; }
}

public class XmlDescriptor
{
public string DescriptorCode { get; set; }
public string DescriptorCodeStartDate { get; set; }
public string DescriptorCodeEndDate { get; set; }
}

...所以上面的 XML 片段将转换为:

var coverageCd = new XmlCoverageCode
{
CoverageCode = "WEL",
Descriptors =
new List<XmlDescriptor>
{
new XmlDescriptor
{
DescriptorCode = "SMIO",
DescriptorCodeStartDate = "01/01/2015",
DescriptorCodeEndDate = "12/31/9999"
},
new XmlDescriptor
{
DescriptorCode = "AAE",
DescriptorCodeStartDate = "01/01/2015",
DescriptorCodeEndDate = "12/31/9999"
}
}
};

当然,我更愿意使用内置机制来执行此操作。我只是不知道这是否可能。

最佳答案

要从 XML 中获取类,您只需将 XML 复制到剪贴板,然后在 Visual Studio 中进行编辑 -> 选择性粘贴 -> 将 XML 作为类粘贴。然后,在清理生成的代码后,我们得到以下内容:

[XmlRoot(ElementName = "coverageCd")]
public partial class XmlCoverageCode
{
[XmlText]
public string CoverageCode { get; set; }

[XmlElement("descriptorCd")]
public List<XmlDescriptor> Descriptors { get; set; }
}

public partial class XmlDescriptor
{
[XmlText]
public string DescriptorCode { get; set; }

[XmlElement("descriptorCdStartDate")]
public string DescriptorCodeStartDate { get; set; }

[XmlElement("descriptorCdEndDate")]
public string DescriptorCodeEndDate { get; set; }
}

这实际上与您在问题中所写的相同,但是具有必需的属性并将 IEnumerable 更改为 List,因为 XmlSerializer不支持第一个。

以及如何序列化/反序列化的代码片段:

var serializer = new XmlSerializer(typeof(XmlCoverageCode));
var coverageCode = (XmlCoverageCode)serializer.Deserialize(xmlFileStream);
serializer.Serialize(xmlFileStream, coverageCode);

关于c# - 当它们不是 "shaped"时将 XML 反序列化为对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31626694/

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