在Serializable C#类上使用XmlArrayItem属性而不使用XmlArray

时间:2010-07-21 19:44:06

标签: c# xml xml-serialization serializable xml-deserialization

我希望XML格式如下:

<configuration><!-- Only one configuration node -->
  <logging>...</logging><!-- Only one logging node -->
  <credentials>...</credentials><!-- One or more credentials nodes -->
  <credentials>...</credentials>
</configuration>

我正在尝试创建一个具有Configuration属性的类[Serializable]。要序列化凭证节点,我有以下内容:

[XmlArray("configuration")]
[XmlArrayItem("credentials", typeof(CredentialsSection))]
public List<CredentialsSection> Credentials { get; set; }

但是,当我将其序列化为XML时,XML的格式如下:

<configuration>
  <logging>...</logging>
  <configuration><!-- Don't want credentials nodes nested in a second
                      configuration node -->
    <credentials>...</credentials>
    <credentials>...</credentials>
  </configuration>
</configuration>

如果我删除[XmlArray("configuration")]行,我会收到以下内容:

<configuration>
  <logging>...</logging>
  <Credentials><!-- Don't want credentials nodes nested in Credentials node -->
    <credentials>...</credentials>
    <credentials>...</credentials>
  </Credentials>
</configuration>

如何在单个根节点<credentials>中使用多个<configuration>节点,按照我想要的方式对其进行序列化?我想这样做而不必实现IXmlSerializable并进行自定义序列化。这就是我的课程描述方式:

[Serializable]
[XmlRoot("configuration")]
public class Configuration : IEquatable<Configuration>

1 个答案:

答案 0 :(得分:74)

以下内容应按您希望的方式正确序列化。列表中的线索为[XmlElement("credentials")]。我通过获取xml,在Visual Studio中从中生成模式(xsd)来完成此操作。然后在架构上运行xsd.exe以生成类。 (还有一些小编辑)

public class CredentialsSection
{
    public string Username { get; set; }
    public string Password { get; set; }
}

[XmlRoot(Namespace = "", IsNullable = false)]
public class configuration
{
    /// <remarks/>
    public string logging { get; set; }

    /// <remarks/>
    [XmlElement("credentials")]
    public List<CredentialsSection> credentials { get; set; }

    public string Serialize()
    {
        var credentialsSection = new CredentialsSection {Username = "a", Password = "b"};
        this.credentials = new List<CredentialsSection> {credentialsSection, credentialsSection};
        this.logging = "log this";
        XmlSerializer s = new XmlSerializer(this.GetType());
        StringBuilder sb = new StringBuilder();
        TextWriter w = new StringWriter(sb);
        s.Serialize(w, this);
        w.Flush();
        return sb.ToString();
    }
}

提供以下输出

<?xml version="1.0" encoding="utf-16"?>
<configuration xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <logging>log this</logging>
  <credentials>
    <Username>a</Username>
    <Password>b</Password>
  </credentials>
  <credentials>
    <Username>a</Username>
    <Password>b</Password>
  </credentials>
</configuration>