Reputation: 26919
To be able to serialize and deserialize a XML I had designed like this:
<?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>
I had written two classes like this below:
public class DbConnectionInfo
{
public string ServerName { get; set; }
}
and
[Serializable]
[XmlRoot("DbConnections")]
public class DbConnections: List<DbConnectionInfo>
{
//...
}
Now I want to expand my XML form and add one more field like this but is there is a way to design my class in a way that I don' have to REPEAT it in every XML tag? like this:
<?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>
So I just really added that one line to previous XML: But my question is how should I modify my classes to add this? And is it even possible or a correct design?
<UseWindowsAuthentication>Yes</UseWindowsAuthentication>
Upvotes: 0
Views: 622
Reputation: 6348
Maybe something like this
[Serializable]
[XmlRoot("DbConnections")]
public class DbConnections
{
List<DbConnectionInfo> DbConnectionInfos;
Boolean UseWindowsAuthentication;
}
Edited to add: if you do not want nested elements, decorate your class as so
public class DbConnections
{
[XmlElement("DbConnectionInfo")]
public List<DbConnectionInfo> DbConnectionInfos;
public Boolean UseWindowsAuthentication;
}
I tested this and the following xml was serialized
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
Upvotes: 1