简体   繁体   中英

xml list deserialization only take one element

I am loading path of different types from this xml file :

<?xml version="1.0" encoding="utf-8" ?>
<SplashScreen>
  <Image>
    <Path>Visual/Screens/SplashScreen/samurai1024-768</Path>
    <Path>Visual/Screens/SplashScreen/Humanoid1024-768</Path>
  </Image>
  <Song>
    <Path>Audio/SplashScreen/wardrums</Path>
  </Song>
</SplashScreen>

This is my XmlManager class that I use to serialize and Deserialize :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace Lucid.Classes
{
    public class XmlManager<T>
    {
        public Type Type;

        public T Load(string P_path)
        {
            T instance;
            using (TextReader reader = new StreamReader(P_path))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(Type);
                instance = (T)xmlSerializer.Deserialize(reader);
            }
            return instance;
        }

        public void Save(string P_path, object P_obj)
        {
            using (TextWriter writer = new StreamWriter(P_path))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(Type);
                xmlSerializer.Serialize(writer, P_obj);
            }
        }
    }
}

this is the class I am deserializing into :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Lucid.Classes
{
    [XmlRoot("SplashScreen")]
    public class SerializableSplashScreen
    {
        [XmlElement("Image")]
        public List<string> imgPathList { get; set; }
        [XmlElement("Song")]
        public List<string> songPathList { get; set; }
    }
}

Somehow, it only takes in the first path in image and doesn't record the rest. Am I doing something wrong?

Ok I found the solution. The problem was in the xml file. The correct way to write it is :

<?xml version="1.0" encoding="utf-8" ?>
<SplashScreen>
  <Image>Visual/Screens/SplashScreen/samurai1024-768</Image>
  <Image>Visual/Screens/SplashScreen/Humanoid1024-768</Image>
  <Song>Audio/SplashScreen/wardrums</Song>
</SplashScreen>

Try this class definition and you should be able to properly deserialize you XML:

[Serializable]
[XmlRoot("SplashScreen")]
public class SerializableSplashScreen
{
    [XmlElement]
    public Image Image { get; set; }

    [XmlElement]
    public Song Song { get; set; }
}

[Serializable]
public class IsPath
{
    [XmlElement]
    public List<string> Path { get; set; }
}

[Serializable]
public class Image : IsPath
{
}

[Serializable]
public class Song : IsPath
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM