49

次の形式の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>
4

1 に答える 1

80

以下は、希望する方法で適切にシリアル化する必要があります。[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>
于 2010-07-21T20:15:37.973 に答える