c#-如何基于元素的值反序列化xml到派生类?
作者:互联网
例如,我有一个xml:
<MyFruit>
<Fruit>
<Name>Apple</Name>
<Size>Big</Size>
</Fruit>
<Fruit>
<Name>Orange</Name>
<Price>10.00</Price>
</Fruit>
</MyFruit>
您可能会注意到,水果节点包含不同的元素,这是我的伤害:(
然后,我定义了以下类以容纳反序列化的对象:
public class MyFruit
{
public List<Fruit> Fruits { get; set; }
}
public abstract class Fruit
{
public string Name { get; set; }
}
public class Apple : Fruit
{
public string Size { get; set; }
}
public class Orange : Fruit
{
public float Price { get; set; }
}
没用
我也尝试过:
>在水果基类中添加[XmlInclude(typeof(Apple))]和[XmlInclude(typeof(Orange))]属性以指定具体的派生类
>将[XmlElement(typeof(Apple))]和[XmlElement(typeof(Orange))属性添加到MyFruit类的Fruits属性中
它们都不起作用.
因此,我想知道是否有一种方法可以控制基于元素值的反序列化过程(如果名称为Apple,反序列化为Apple类,从Orange转换为Orange类…),或者是否有更好的方法?
更新
我写了一个扩展方法来反序列化xml:
public static T Deserialize<T>(this string xml)
{
if (string.IsNullOrEmpty(xml))
{
return default(T);
}
try
{
var xmlserializer = new XmlSerializer(typeof(T));
var stringReader = new StringReader(xml);
using (var reader = XmlReader.Create(stringReader))
{
return (T) xmlserializer.Deserialize(reader);
}
}
catch (Exception ex)
{
throw new Exception("反序列化发生错误", ex);
}
}
解决方法:
一种方法是简单地通过XslCompiledTransform类将输入xml转换为可以轻松反序列化为所需对象结构的格式.下面的示例演示了该概念:
// XML Deserialization helper.
class XmlSerializationHelper
{
// Transform the input xml to the desired format needed for de-serialization.
private static string TransformXml(string xmlString)
{
// XSL transformation script.
string xsl = @"<xsl:stylesheet xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" version=""1.0"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<xsl:template match=""MyFruit"">
<xsl:element name=""{local-name()}"">
<Fruits>
<xsl:for-each select=""Fruit"">
<xsl:element name=""Fruit"">
<xsl:attribute name=""xsi:type""><xsl:value-of select=""Name""/></xsl:attribute>
<xsl:copy-of select=""./node()""/>
</xsl:element>
</xsl:for-each>
</Fruits>
</xsl:element>
</xsl:template>
</xsl:stylesheet>";
// Load input xml as XmlDocument
XmlDocument sourceXml = new XmlDocument();
sourceXml.LoadXml(xmlString);
// Create XSL transformation.
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(new XmlTextReader(new StringReader(xsl)));
// Apply transformation to input xml and write result out to target xml doc.
XmlDocument targetXml = new XmlDocument(sourceXml.CreateNavigator().NameTable);
using (XmlWriter writer = targetXml.CreateNavigator().AppendChild())
{
transform.Transform(sourceXml, writer);
}
// Return transformed xml string.
return targetXml.InnerXml;
}
public static T DeSerialize<T>(string inputXml)
{
T instance = default(T);
if (string.IsNullOrEmpty(inputXml))
return instance;
try
{
string xml = TransformXml(inputXml); // Transform the input xml to the desired xml format needed to de-serialize objects.
string attributeXml = string.Empty;
using (StringReader reader = new StringReader(xml))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (XmlReader xmlReader = new XmlTextReader(reader))
{
instance = (T)serializer.Deserialize(xmlReader);
xmlReader.Close();
}
reader.Close();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return instance;
}
}
现在可以按如下方式使用helper类:
string inputXml = @"<MyFruit>
<Fruit>
<Name>Apple</Name>
<Size>Big</Size>
</Fruit>
<Fruit>
<Name>Orange</Name>
<Price>10.00</Price>
</Fruit>
</MyFruit>";
MyFruit fruits = XmlSerializationHelper.DeSerialize<MyFruit>(inputXml);
标签:xml-deserialization,c 来源: https://codeday.me/bug/20191118/2026083.html