将新字段添加到要序列化的类中

时间:2016-02-26 18:59:19

标签: c# xml serialization

为了能够序列化和反序列化我设计的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>

1 个答案:

答案 0 :(得分:1)

也许是这样的

[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>

Here is a link to more info on decorating for xml serialization