以下内容应按您希望的方式正确序列化。线索正在
[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>