[英]mixed type property serialization to xml in C#
For example I have three classes例如我有三个班级
public class A
{
public string Abc { get; set; }
}
public class B
{
public string Xyz { get; set; }
}
public class C
{
private object itemField;
[XmlElement("A", typeof(A))]
[XmlElement("B", typeof(B))]
public object Item
{
get
{
return itemField;
}
set
{
itemField = value;
}
}
}
And I'm trying to serialize an instance of class C我正在尝试序列化 C 类的实例
var b = new B
{
Xyz = "123123"
};
var c = new C
{
Item = b
};
var serializer = new XmlSerializer<C>();
var aaa = serializer.Serialize(c);
Then the output is然后输出是
-C -C
-- A --A
---Xyz ---XYZ
----123123 ----123123
---/Xyz ---/XYZ
-- /A -- /A
-/C -/C
But I'm expecting但我期待
-C -C
-- B --乙
---Xyz ---XYZ
----123123 ----123123
---/Xyz ---/XYZ
-- /B -- /B
-/C -/C
How can I do this?我怎样才能做到这一点? (I converted amazon mws xsd's to classes with xsd.exe, and some output classes are like C class, so I'm having trouble while trying to serialize these classes.)
(我使用 xsd.exe 将 amazon mws xsd 转换为类,并且一些输出类类似于 C 类,因此我在尝试序列化这些类时遇到了问题。)
I'm using net framework 4.6.1 and for serialization XSerializer( nuget.org/packages/XSerializer/0.4.2 ).我正在使用网络框架 4.6.1 和序列化 XSerializer( nuget.org/packages/XSerializer/0.4.2 )。
*** EDIT: I found the problem, the problem is not the serializer. *** 编辑:我发现了问题,问题不是序列化程序。 "xsd.exe" made mistakes on multidimensional arrays while converting xsd files.
“xsd.exe”在转换 xsd 文件时在多维数组上出错。 I edited the classes for serialization attributes and it worked.
我编辑了序列化属性的类并且它起作用了。 Example:
例子:
// I changed "[XmlArrayItem("Name", typeof(TypeName))]" To that:
[XmlArrayItem("Name", typeof(TypeName[]))]
public TypeName[][] PropName { get; set; }
Thanks for everyone谢谢大家
I don't know about that nuget, but serializing without nugets (I've used extension method from this post ):我不知道那个 nuget,但是在没有 nuget 的情况下进行序列化(我使用了这篇文章中的扩展方法):
var test = SerializeObject<C>(c);
produces expected result产生预期结果
<?xml version="1.0" encoding="utf-16"?>
<C xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<B>
<Xyz>123123</Xyz>
</B>
</C>
I am getting the desired results with XmlSerializer
.我用
XmlSerializer
得到了想要的结果。 Namespace System.Xml.Serialization
命名空间
System.Xml.Serialization
var writer = new XmlSerializer(typeof(C));
var file = File.Create(strfilepath);
writer.Serialize(file, c);
file.Close();
Output输出
<?xml version="1.0"?>
<C xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<B>
<Xyz>123123</Xyz>
</B>
</C>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.