C#获取具有相同名称的所有元素的列表 - XML Deserialize

时间:2016-11-01 21:30:38

标签: c# xml serialization unity3d deserialization

我尝试获取XML文件中所有声音元素的列表。

我得到了所有标记但是当我试图获得标签声音的所有元素时,我什么也得不到。该列表始​​终为0.

Root Class

[XmlArray("markers")]
[XmlArrayItem("marker")]
public List<WaypointInfo> markers = new List<WaypointInfo>();

[XmlArray("pattern")]
[XmlArrayItem("sound")]
public List<SoundInfo> soundsInfo = new List<SoundInfo> ();

/// <summary>
/// The file extension.
/// </summary>
public static readonly string fileExtensionMp3 = "*.mp3";

public static FileLoader loadInformationXML(string filePath){

    //Define the rootclass
    XmlSerializer serializer = new XmlSerializer (typeof(FileLoader));

    //Create inputstream
    FileStream fl = new FileStream (filePath, FileMode.Open);

    //Extract the stream and save it into our root class
    FileLoader xmlData = serializer.Deserialize (fl) as FileLoader;

    //Close the inputstream
    fl.Close ();

    return xmlData;
}

标记arraylist是正确的,但另一个声音列表始终为空。

类WaypointsInfo

using UnityEngine;
using System.Collections.Generic;
using System.Xml.Serialization;

public class WaypointInfo {

    [XmlAttribute("name")]
    public string markerName;

    public Pattern pattern = new Pattern();

}

Class Soundinfo

using UnityEngine;
using System.Xml.Serialization;
using System.Collections;

public class SoundInfo {

    /// <summary>
    /// The minimum distance that triggers this sound.
    /// </summary>
    [XmlAttribute("distance")]
    public float distance; 

    /// <summary>
    /// When this sound has been played the last time, in runtime milliseconds.
    /// </summary>
    public float lastPlayed;

    /// <summary>
    /// If this sound should be looped.
    /// </summary>
    public bool looped;
}

和xml文件

   <soundpackage>
    <markers>
        <marker name="bird">
            <pattern name="aPattern">
                <sound distance="10">bird.mp3</sound>
                <sound distance="10">bird.mp3</sound>
            </pattern>
        </marker>
    </markers>
</soundpackage>

1 个答案:

答案 0 :(得分:0)

您的根节点是否具有此xmlns=http;//somepath之类的代码?然后你正在处理命名空间。当您获得零结果并且您确定正确引用它时,必须考虑命名空间。

我不熟悉Xml序列化。所以我查找了XML序列化的名称空间。这是另一个StackOverflow线程的示例。

有关名称空间的序列化答案,请参阅this answer