在Serializable C#类中使用不带XmlArray的XmlArrayItem属性
我想用以下格式的XML:
<configuration><!-- Only one configuration node --> <logging>...</logging><!-- Only one logging node --> <credentials>...</credentials><!-- One or more credentials nodes --> <credentials>...</credentials> </configuration>
我想创build一个具有[Serializable]
属性的类Configuration
。 要序列化凭证节点,我有以下几点:
[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>
我怎样才能以我想要的方式序列化这个,在单根节点<configuration>
有多个<credentials>
节点? 我想这样做,而不必实现IXmlSerializable
和自定义序列化。 这就是我的class级的描述:
[Serializable] [XmlRoot("configuration")] public class Configuration : IEquatable<Configuration>
以下应该按照你想要的方式正确地序列化。 线索是列表上的[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>