代码之家  ›  专栏  ›  技术社区  ›  Yushox

xmlSerialize两个不同对象的列表

  •  1
  • Yushox  · 技术社区  · 12 年前

    我需要帮助来序列化两个列表并将它们写入xml文件。 我尝试的代码是

    XmlSerializer xs = new XmlSerializer(typeof(List<OtherAction>));
    XmlSerializer xsActions = new XmlSerializer(typeof(List<Action>));
    using (StreamWriter sw = new StreamWriter("actions.xml"))
    {
       xs.Serialize(sw, listOtherActions);
       xsActions.Serialize(sw, listActions);
    }
    

    但它先写listOtherActions,然后写listActions。所以它在xml文件上创建了2个根 我想做的是只有一个根节点和两个列表。

    1 回复  |  直到 12 年前
        1
  •  1
  •   yogi    12 年前

    为什么不创建一个同时包含两种List类型的类并序列化该类。如下图所示。

    public class Combined
    {
     public List<OtherAction> otherActions{get; set;}
     public List<Action> actions{get; set;}
    }
    
    
    XmlSerializer xs = new XmlSerializer(typeof(List<Combined>));
    using (StreamWriter sw = new StreamWriter("CombinedActions.xml"))
    {
       xs.Serialize(sw, listCombinedActions);
    }
    
    推荐文章