当 "shaped" 不相同时反序列化 XML 以反对?

Deserializing XML to object when they are not "shaped" the same?

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

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

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"
            }
        }
};

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

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

  • 运行 xsd.exe test.xml 生成模式,例如test.xsd
  • 运行 xsd.exe /c test.xsd 从模式
  • 生成 classes

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

[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不支持第一个.

代码片段如何 serialize/deserialize:

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