当XML没有“形状”相同时,将XML反序列化为对象?

时间:2015-07-25 12:57:37

标签: c# xml serialization deserialization

我有一个像这样的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"
            }
        }
};

当然,我更愿意使用内置机制来做到这一点。我只是不知道这是否可能。

2 个答案:

答案 0 :(得分:3)

要从XML获取类,您只需将XML复制到剪贴板中并进行编辑 - &gt;选择性粘贴 - &gt;在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);

答案 1 :(得分:0)

您可以使用xsd命令将xml转换为c#类 将xml保存在文件test.xml

  • 运行xsd.exe test.xml以生成架构,例如test.xsd
  • 运行xsd.exe / c test.xsd以从架构生成类