向要序列化的类添加新字段

本文关键字:字段 新字段 添加 序列化 | 更新日期: 2023-09-27 18:36:29

为了能够序列化和反序列化我设计的XML:

<?xml version="1.0" encoding="utf-8"?>
<DbConnections xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <DbConnectionInfo>
    <ServerName>SQLServer2k8</ServerName>
  </DbConnectionInfo>
  <DbConnectionInfo>
    <ServerName>SQLServer2k8R2</ServerName>
  </DbConnectionInfo>
</DbConnections>

我在下面写了两个这样的类:

public class DbConnectionInfo
{
    public string ServerName { get; set; }
}

[Serializable]
[XmlRoot("DbConnections")]
public class DbConnections: List<DbConnectionInfo>
{
  //...
}

现在我想扩展我的 XML 表单并再添加一个这样的字段,但是有没有办法以一种我不必在每个 XML 标记中重复它的方式设计我的类? 像这样:

<?xml version="1.0" encoding="utf-8"?>
<DbConnections xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <DbConnectionInfo>
    <ServerName>SQLServer2k8</ServerName>
  </DbConnectionInfo>
  <DbConnectionInfo>
    <ServerName>SQLServer2k8R2</ServerName>
  </DbConnectionInfo>
   <UseWindowsAuthentication>Yes</UseWindowsAuthentication>
</DbConnections>

所以我真的在以前的 XML 中添加了一行:但我的问题是我应该如何修改我的类来添加它? 甚至可能或正确的设计吗?

<UseWindowsAuthentication>Yes</UseWindowsAuthentication>

向要序列化的类添加新字段

也许是这样的

[Serializable]
[XmlRoot("DbConnections")]
public class DbConnections
{
   List<DbConnectionInfo> DbConnectionInfos;
   Boolean UseWindowsAuthentication;
}

编辑以添加:如果您不想要嵌套元素,请按原样装饰您的类

public class DbConnections
{
    [XmlElement("DbConnectionInfo")]
    public List<DbConnectionInfo> DbConnectionInfos;
    public Boolean UseWindowsAuthentication;
}

我对此进行了测试,并序列化了以下xml。

XmlSerializer serializer = new XmlSerializer(typeof(DbConnections));
            string xml;
            using (StringWriter textWriter = new StringWriter())
            {
                serializer.Serialize(textWriter, oDbConnections);
                xml = textWriter.ToString();
            }
<?xml version="1.0" encoding="utf-16"?>
<DbConnections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <DbConnectionInfo>
    <ServerName>test</ServerName>
  </DbConnectionInfo>
  <DbConnectionInfo>
    <ServerName>test 2</ServerName>
  </DbConnectionInfo>
  <UseWindowsAuthentication>true</UseWindowsAuthentication>
</DbConnections>

下面是有关 xml 序列化修饰的详细信息的链接