c#获得所有同名元素的列表——XML反序列化

本文关键字:列表 XML 反序列化 元素 | 更新日期: 2023-09-27 18:15:48

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

我得到了所有的标记,但当我试图得到所有的元素与标签声音我没有得到任何东西。列表始终为0。

根类

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

标记数组列表是正确的,但是其他的声音列表总是空的。

类WaypointsInfo

using UnityEngine;
using System.Collections.Generic;
using System.Xml.Serialization;
public class WaypointInfo {
    [XmlAttribute("name")]
    public string markerName;
    public Pattern pattern = new Pattern();
}
类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>

c#获得所有同名元素的列表——XML反序列化

您的根节点是否有这样的代码xmlns=http;//somepath ?然后处理名称空间。当您得到零结果并且您确定正确引用它时,必须考虑名称空间。

我不熟悉Xml序列化。因此,我查找XML序列化的名称空间。下面是另一个StackOverflow线程的例子。