How to map two list values ​​in the class object using xml serialization

advertisements

i have two list of elements with same length eg.

List 1: profile1, profile2,profile3

List 2: 1,0,1

these lists are the public property in class objects. i.e:

class Serviceinfo
{
[xmlArray("Profiles")]
[xmlArrayItem("Profile")]
public list<string> Profiles;
public list<int> state;

}

here i need to map each profile with its state. eg.

<serviceinfo>
 <profiles>
     <profile>profile1</profile>
     <state>1</state>
 </profiles>
<profiles>
      <profile>profile2</profile>
     <state>0</state>
 </profiles>
<profiles>
      <profile>profile3</profile>
     <state>1</state>
 </profiles>
</serviceinfo>

how do i change my class object, to return the above xml result. is it possible to get the above output in xml serialization method.


I'm not sure if it can be done using XmlSerializer because your desired XML structure is quite strange when compared with your class.

But it definitely can be done using LINQ to XML:

var serviceInfo = new Serviceinfo { Profiles = new List<string> { "one", "two", "three" }, state = new List<int> { 1, 2, 4 } };

var xml = new XDocument(
            new XElement("serviceinfo",
                serviceInfo.Profiles
                           .Zip(serviceInfo.state, (p, s) => new { p, s })
                           .Select(x =>
                               new XElement("profiles",
                                   new XElement("profile", x.p),
                                   new XElement("state", x.s.ToString())))));

If you really want to XML Serialization you should change your class structure to

[XmlRoot(ElementName = "serviceInfo")]
public class Serviceinfo
{
    [XmlElement("profiles")]
    public List<Profile> Profiles { get; set; }
}

public class Profile
{
    [XmlElement(ElementName = "profile")]
    public string Name { get; set; }
    [XmlElement(ElementName = "state")]
    public int State { get; set; }
}

and use XmlSerializer:

var serviceInfo = new Serviceinfo
{
    Profiles = new List<Profile>() {
        new Profile { Name = "one", State = 1 },
        new Profile { Name = "two", State = 2 }
    }
};

var writer = new StringWriter();
var serializer = new XmlSerializer(typeof(Serviceinfo));

serializer.Serialize(writer, serviceInfo);

var xml = writer.ToString();