[英]Deserialize multiple but “different” XML elements with the same name through XmlSerializer class in C#
[英]C# XmlSerializer Serialize the same class with different namespaces
假设我有一个 class:
using System.Xml;
using System.Xml.Serialization;
class Foo {
[XmlElement(ElementName="Bar")]
public string Bar {get; set;}
}
现在我想序列化它。 但。 我想指定不同的命名空间,有一次我希望我的 XML 看起来像这样:
<Foo xmlns:v1="http://site1">
<v1:Bar />
</Foo>
而在另一个 - 像这样:
<Foo xmlns:v2="http://site2">
<v2:Bar />
</Foo>
我知道我需要在 XmlElement 属性中指定命名空间,但这正是我想要避免的。 当然,我可以创建 2 个不同的类,除了字段属性之外它们是相同的,但这在某种程度上感觉是错误的。 有什么办法可以强制 XmlSerializer 使用我在运行时选择的命名空间?
是的; XmlAttributeOverrides
:
static void Main()
{
var obj = new Foo { Bar = "abc" };
GetSerializer("http://site1").Serialize(Console.Out, obj);
Console.WriteLine();
GetSerializer("http://site2").Serialize(Console.Out, obj);
}
static XmlSerializer GetSerializer(string barNamespace)
{
var ao = new XmlAttributeOverrides();
var a = new XmlAttributes();
a.XmlElements.Add(new XmlElementAttribute { Namespace = barNamespace });
ao.Add(typeof(Foo), nameof(Foo.Bar), a);
return new XmlSerializer(typeof(Foo), ao);
}
然而!!!
执行此操作时,它每次都会在 memory 中生成一个附加程序集; 您必须缓存并重用序列化程序实例 - 通常通过并发字典或类似的方式。 例如:
private static readonly ConcurrentDictionary<string, XmlSerializer>
s_serializersByNamespace = new();
static XmlSerializer GetSerializer(string barNamespace)
{
if (!s_serializersByNamespace.TryGetValue(barNamespace, out var serializer))
{
lock (s_serializersByNamespace)
{
// double-checked, avoid dups
if (!s_serializersByNamespace.TryGetValue(barNamespace, out serializer))
{
var ao = new XmlAttributeOverrides();
var a = new XmlAttributes();
a.XmlElements.Add(new XmlElementAttribute { Namespace = barNamespace });
ao.Add(typeof(Foo), nameof(Foo.Bar), a);
serializer = new XmlSerializer(typeof(Foo), ao);
s_serializersByNamespace[barNamespace] = serializer;
}
}
}
return serializer;
}
注意:如果你也想要特定的xmlns
控件,那就是XmlSerializerNamespaces
:
var obj = new Foo { Bar = "abc" };
var ns = new XmlSerializerNamespaces();
ns.Add("v1", "http://site1");
GetSerializer("http://site1").Serialize(Console.Out, obj, ns);
Console.WriteLine();
ns = new XmlSerializerNamespaces();
ns.Add("v2", "http://site2");
GetSerializer("http://site2").Serialize(Console.Out, obj, ns);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.