如何使用xml序列化在类对象中映射两个列表值

时间:2014-01-15 06:09:25

标签: c# xml xml-serialization

我有两个长度相同的元素列表,例如。

List 1: profile1, profile2,profile3

List 2: 1,0,1

这些列表是类对象中的公共属性。 即:

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

}

这里我需要将每个配置文件映射到其状态。例如。

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

如何更改我的类对象,以返回上面的xml结果。是否可以在xml序列化方法中获得上述输出。

2 个答案:

答案 0 :(得分:0)

我不确定是否可以使用XmlSerializer来完成,因为与您的课程相比,您所需的XML结构非常奇怪。

但绝对可以使用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())))));

如果您真的想要XML序列化,则应将类结构更改为

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

并使用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();

答案 1 :(得分:0)

@Gomathipriya:根据我对你的问题的理解,最好的解决方案是创建一个单独的集合,将两个值作为属性,如下例所示,然后将整个集合转换为XML。

将Collection转换为XML:http://www.dotnetcurry.com/showarticle.aspx?ID=428

示例C#代码:

class Program
{
    public static void Main(string[] args)
    {

        List<string> Profiles = new List<string>();
        List<int> state = new List<int>();

        // Just filling the entities as per your needs
        for (int i = 0; i < 5; i++)
        {
            Profiles.Add("P-" + i.ToString());
            state.Add(i);
        }

        listOfProfileState ProfileStateColl = new listOfProfileState();
        for (int i = 0; i < Profiles.Count; i++)
        {
            ProfileStateColl.Add(new ProfileState() { Profile = Profiles[i], State = state[i] });
        }
    }
}

public class ProfileState
{
    public string Profile { get; set; }
    public int State { get; set; }
}

public class listOfProfileState : List<ProfileState>
{

}

根据上面提到的示例,如果您将集合'ProfileStateColl'转换为XML,您将获得所需的解决方案。 :)