当XML未“成形”时,将其反序列化为对象.相同的
本文关键字:反序列化 对象 XML 成形 | 更新日期: 2023-09-27 18:04:51
我有一个像这样的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中使用Edit -> Paste Special -> Paste XML As classes 。然后,在清理生成的代码之后,我们得到以下内容:
[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);
可以使用xsd命令将xml转换为c#类将xml保存在test.xml
文件中- 运行xsd.exe test.xml生成模式,例如test.xml。xsd
- 运行xsd.exe/c test。从模式 生成类