将多个XML标记反序列化为单个c#对象
本文关键字:单个 对象 反序列化 XML | 更新日期: 2023-09-27 18:12:55
我的类结构如下
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数据反序列化到不同的对象,但不能在单个对象中。请帮助。
如果您自己创建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没有"price"answers"color"属性,这些属性应该使用创建的Common instance
下面是使用您提供的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; }
}
这将给你一个单一的对象与所有你需要的元素