将specyfic XML文件解析为c#(Unity)中的对象

时间:2017-11-14 10:04:16

标签: c# xml

我想将XML文件反序列化为对象,但我的XML看起来像这样

<ALLObjects>
<object ID ="1">
    <param1>Clicks</param1>
    <param2>NONE</param2>
    <param3>example</param3>
    <param4>example23</param4>
    <param5>1</param5>
    <param6>1</param6>
</object>

<object ID ="2">
    <param1>Clicks</param1>
    <param2>NONE</param2>
    <param3>Example23</param3>
    <param4>Example 1</param4>
    <param5>10</param5>
    <param6>1</param6>
</object>

 //more objects

</ALLObjects>

我有一个包含所有参数的模型(包括ID值)。我想将所有对象加载到列表中并进行一些更改,然后将其保存到同一XML文件中。我知道当XML是这种格式的时候它是如何工作的

<object >
<ID>1</ID>
<param1>Clicks</param1>
<param2>NONE</param2>
<param3>example</param3>
<param4>example23</param4>
<param5>1</param5>
<param6>1</param6>
</object>

但我不想手动重写整个文件以将其加载到该格式中。我需要提示这个案例最好的条件是什么。也许我需要将它加载到json中然后解析到对象中?

@chade_目前我尝试使用XmlSerializer,但我遇到了错误

InvalidOperationException: <achievements xmlns=''> was not expected

我的代码:LoadingFromFile

  private void LoadData()
    {
        List<AchivmentModel> models;
        using (var reader = new StreamReader("test.xml"))
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(List<AchivmentModel>),
                new XmlRootAttribute("ALLObjects"));
            models = (List<AchivmentModel>)deserializer.Deserialize(reader);
        }
    }


[System.Serializable, XmlRoot("ALLObjects")]
public class AchivmentList
{
    public AchivmentList() { Items = new List<AchivmentModel>(); }
    [XmlElement("object")]
    public List<AchivmentModel> Items { get; set; }
}



[System.Serializable, XmlType( "object ")]
public class AchivmentModel
{
    public AchivmentModel() { }

    [XmlElement("ID")]
    public int ID { get; set; }
    [XmlElement("param1")]
    public string Progress { get; set; }
    [XmlElement("param2")]
    public string Reward { get; set; }

    [XmlElement("param3")]
    public string Title { get; set; }
    [XmlElement("param4")]
    public string Description { get; set; }
    [XmlElement("param5")]
    public int param6{ get; set; }
    [XmlElement("param6")]
    public int AchivmentAnimalSubtitle { get; set; }

}
}

1 个答案:

答案 0 :(得分:0)

如果要加载属性值而不是XML中的元素,则需要使用[XmlAttribute]在模型类中修饰属性:

此型号:

[System.Serializable, XmlType( "object")]
public class AchivmentModel
{
    // serialize attribute on the XmlNode
    [XmlAttribute("ID")]
    public int ID { get; set; }
    // serialize an element value
    [XmlElement("param1")]
    public string Progress { get; set; }
    // other properties omitted
}

将从此XML反序列化:

<object ID="2"> <!-- Deserialize ID with XmlAttribute -->
    <param1>Clicks</param1>  <!-- deserialize with XmlElement -->
    <!-- other elements omitted -->
</object>