将多个XML标记反序列化为单个C#对象

时间:2016-10-13 07:44:35

标签: c# xml serialization xml-deserialization

我的课程结构如下

   public class Common
    {
        public int price { get; set; }
        public string color { get; set; }
    }
    public class SampleProduct:Common
    {
        public string sample1 { get; set; }
        public string sample2 { get; set; }
        public string sample3 { get; set; }
    }

我有XML文件如下

<ConfigData>
  <Common>
    <price>1234</price>
    <color>pink</color>    
  </Common>
  <SampleProduct>
    <sample1>new</sample1>
    <sample2>new</sample2>
    <sample3>new123</sample3>
  </SampleProduct>
</ConfigData>

现在我想将完整的XML数据反序列化为SampleProduct对象(单个对象)。我可以将XML数据反序列化为不同的对象,但不能反序列化为单个对象。请帮忙。

2 个答案:

答案 0 :(得分:0)

如果您自己创建XML,请执行以下操作:

<ConfigData>
  <SampleProduct>
    <price>1234</price>
    <color>pink</color>    
    <sample1>new</sample1>
    <sample2>new</sample2>
    <sample3>new123</sample3>
  </SampleProduct>
</ConfigData>

否则,如果您从其他来源获取XML,请执行Kayani在其评论中建议的内容:

public class ConfigData
{
    public Common { get; set; }
    public SampleProduct { get; set; }
}

但请不要忘记以这种方式创建的SampleProduct没有&#34;价格&#34;和&#34;颜色&#34;应使用创建的Common实例

设置属性和这些属性

答案 1 :(得分:0)

以下是使用您提供的XML的完整解决方案。

    public static void Main(string[] args)
    {
        DeserializeXml(@"C:\sample.xml");
    }
    public static void DeserializeXml(string xmlPath)
    {
        try
        {
            var xmlSerializer = new XmlSerializer(typeof(ConfigData));
            using (var xmlFile = new FileStream(xmlPath, FileMode.Open))
            {
                var configDataOSinglebject = (ConfigData)xmlSerializer.Deserialize(xmlFile);
                xmlFile.Close();
            }
        }
        catch (Exception e)
        {
            throw new ArgumentException("Something went wrong while interpreting the xml file: " + e.Message);
        }
    }

    [XmlRoot("ConfigData")]
    public class ConfigData
    {
        [XmlElement("Common")]
        public Common Common { get; set; }

        [XmlElement("SampleProduct")]
        public SampleProduct XSampleProduct { get; set; }
    }

    public class Common
    {
        [XmlElement("price")]
        public string Price { get; set; }

        [XmlElement("color")]
        public string Color { get; set; }
    }

    public class SampleProduct
    {
        [XmlElement("sample1")]
        public string Sample1 { get; set; }

        [XmlElement("sample2")]
        public string Sample2 { get; set; }

        [XmlElement("sample3")]
        public string Sample3 { get; set; }
    }

这将为您提供一个包含您需要的所有元素的对象。

相关问题