Xml 使用自定义标签名称序列化不同类的数组
假设我有以下类结构:
[XmlInclude(typeof(CustomNode))]
[XmlInclude(typeof(CustomNode2))]
[XmlRoot("node")]
class Node
{
[XmlElement("node")]
public Node[] Children { get; set; }
}
[XmlRoot("custom-node")]
class CustomNode : Node { }
[XmlRoot("custom-node-2")]
class CustomNode2 : Node { }
我创建以下结构:
var root = new Node { Children = new Node[2] };
root.Children[0] = new CustomNode();
root.Children[1] = new CustomNode2();
当我 Xml 序列化此结构时,我得到以下输出:
<node>
<node xsi:Type="CustomNode"/>
<node xsi:Type="CustomNode2"/>
</node>
但我希望看到(并能够正确加载)这样的内容:
<node>
<custom-node/>
<custom-node-2/>
</node>
是否有可能对于 XmlSerializer?整个问题是因为我打算手动创建源 xml,并试图使其更加人类可读和友好。
Suppose I have the following class structure:
[XmlInclude(typeof(CustomNode))]
[XmlInclude(typeof(CustomNode2))]
[XmlRoot("node")]
class Node
{
[XmlElement("node")]
public Node[] Children { get; set; }
}
[XmlRoot("custom-node")]
class CustomNode : Node { }
[XmlRoot("custom-node-2")]
class CustomNode2 : Node { }
The I create the following structure:
var root = new Node { Children = new Node[2] };
root.Children[0] = new CustomNode();
root.Children[1] = new CustomNode2();
When I Xml serialize this structure, I get following output:
<node>
<node xsi:Type="CustomNode"/>
<node xsi:Type="CustomNode2"/>
</node>
But I would like to see (and be able to load properly) something like this:
<node>
<custom-node/>
<custom-node-2/>
</node>
Is it possible at all for XmlSerializer? The whole problem is because I intend to manually create source xml, and am trying to make it more humanreadble and friendly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我为您的问题找到了一个解决方案,这几乎正是您所需要的:
结果:
希望能有所帮助。
I found a solution for your problem which is nearly what you need:
results in:
Hope that helps a bit.
如果您仅使用各种 xml 属性来指定 xml,我认为您无法说服
XmlSerializer
输出此 xml。如果类型本身不是根(而不是在另一个类中组成),则尝试使用的
[XmlRoot]
属性将被忽略。不过,您可以实现
IXmlSerialized
接口并提供IXmlSerialized.WriteXml
的实现,XmlSerializer
将调用该实现(如果存在)。这将允许您将所需的 xml 直接制作到
XmlWriter
中。如果您还需要反序列化,则还需要为
IXmlSerialized.ReadXml
提供等效实现。I don't think you'll be able persuade the
XmlSerializer
to output this xml if you are only using the various xml attibutes to specify the xml.The
[XmlRoot]
attribute you are attempting to use is ignored if the type is not itself at the root (rather than being composed in another class).However, you can implement the
IXmlSerializable
interface and provide an implementation forIXmlSerializable.WriteXml
, which theXmlSerializer
will call if present.This will allow you to craft the xml you want directly to an
XmlWriter
.If you also need to deserialize, you'll need to provide an equivalent implementation for
IXmlSerializable.ReadXml
as well.