如何在 C# 中使用 XML 序列化包含元素(而非根)的属性

Edd*_*die 5 c# attributes xml-serialization

我需要生成一个如下所示的 XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<inboundMessage xmlns="http://www.myurl.net">
  <header>
    <password>mypwd</password>
    <subscriberId>myuser</subscriberId>
  </header>
  <message xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="myType">
    <eventDate>2012-09-05T12:13:45.561-05:00</eventDate>
    <externalEventId />
    <externalId>SomeIdC</externalId>
  </message>
</inboundMessage>
Run Code Online (Sandbox Code Playgroud)

问题是我不知道如何在标记中包含 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="myType" 。我需要序列化的类是这样的:

[XmlType("inboundMessage")]
[XmlRoot(Namespace = "http://www.myurl.net")]
public class InboundMessage
{
    [XmlElement(ElementName = "header")]
    public Header _header;
    [XmlElement(ElementName = "message")]
    public List<MyType> _messages;
}
Run Code Online (Sandbox Code Playgroud)

我需要将哪些 XmlAttributes 添加到“_messages”成员中才能使其按照我想要的方式序列化?

蒂亚,埃德

Mat*_*ias 1

XmlAttribute像这样使用:

public class MyType
{
    [XmlAttribute("type", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string Type { get; set; }
}
Run Code Online (Sandbox Code Playgroud)