简体   繁体   English

在Unity C#中解析XML文件

[英]Parse XML file in Unity C#

I have a little problem with parsing XML file to object in C#. 我在将XML文件解析为C#对象时遇到了一些问题。 Whole project is in Unity3D. 整个项目都在Unity3D中。 So I have this XML file: 所以我有这个XML文件:

<Questions>
    <Question>
        <questionText>What is this?</questionText>
        <answer>blablabla</answer>
    </Question>
</Questions>

And this is my parsing class: 这是我的解析类:

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

public struct Montage {
    [XmlElement("questionText")]
    public string questionText;

    [XmlElement("answer")]
    public string answer;
}

[XmlRoot("Questions"), XmlType("Questions")]
public class ConfigScene {

    [XmlArray("Questions")]
    [XmlArrayItem("Question")]
    public List<Montage> questions = new List<Montage> ();

    public static ConfigScene Load(string path) {
        try {
            XmlSerializer serializer = new XmlSerializer (typeof(ConfigScene));
            using(FileStream stream = new FileStream(path, FileMode.Open)) {
                 return serializer.Deserialize(stream) as ConfigScene;
            }
        } catch (Exception e) {
             UnityEngine.Debug.LogError ("Exception loading config file: " + e);

             return null;
        }
    }
}

I'm calling this "Load" method in camera Object in Start() method: 我在Start()方法中的Camera Object中将此“ Load”方法称为:

void Start () {
    confScene = ConfigScene.Load(Path.Combine(Application.dataPath, "Config/config2.xml"));
    foreach(Montage o in confScene.questions) {
        Debug.Log (o.questionText);
    }
}

The problem is that my questions list is empty and I didn't get any provided data into it. 问题是我的问题列表为空,没有任何提供的数据。 Do I make something wrong? 我做错什么了吗? Maybe someone made it before and know what is wrong with this code? 也许有人以前做过,知道此代码有什么问题吗?

The XML file schema ( config2.xml ) and the XML serialization attributes in the corresponding class doesn't match. XML文件架构( config2.xml )和相应类中的XML序列化属性不匹配。 Your XML document's root element ( Questions ) and the questions list element are conflicting. XML文档的根元素( Questions )与问题列表元素冲突。

Change your XmlRoot 's ElementName (which is now Questions , line 16 in code) to something else (say Root ). XmlRootElementName (现在是Questions ,代码中的第16行)更改为其他名称(例如Root )。 Accordingly change your config2.xml file's content: enclose the entire document within a Root element as shown below. 相应地更改config2.xml文件的内容:将整个文档包含在Root元素中,如下所示。

<Root>
  <Questions>
    <Question>
      <questionText>What is this?</questionText>
      <answer>blablabla</answer>
    </Question>
  </Questions>
</Root>

Deserialization should be fine now. 反序列化现在应该可以了。

I have to put an answer because I want to add some code here. 我必须回答,因为我想在这里添加一些代码。 So now I can run it and I get data. 因此,现在我可以运行它并获取数据。 But my XML file is more nested. 但是我的XML文件更加嵌套。 Here is the XML file: 这是XML文件:

<?xml version="1.0" encoding="utf-8"?>

<MontageConfig>
    <Parameters>
        <Parameter>
            <mainObject>
                <name>tableTop</name>
            </mainObject>
            <connectors>
                <connector>
                    <name>bolt</name>
                    <count>4</count>
                </connector>
                <connector>
                    <name>spike</name>
                    <count>5</count>
                </connector>
            </connectors>
        </Parameter>
    </Parameters>
</MontageConfig>

And my class: 而我的班级:

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

public struct Connectors {
    [XmlElement("name")]
    public string connectorName;

    [XmlElement("count")]
    public int connectorCount;
}

public struct Montage
{
    [XmlElement("mainObject")]
    [XmlElement("name")]
    public string name;

    [XmlElement("connectors")]
    [XmlElement("connector")]
    public List<Connectors> connectors;

}

[XmlRoot("MontageConfig")]
public class ConfigScene
{

    [XmlArray("Parameters")]
    [XmlArrayItem("Parameter")]
    public List<Montage> questions = new List<Montage>();

    public static ConfigScene Load(string path)
    {
        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(ConfigScene));
            using (FileStream stream = new FileStream(path, FileMode.Open))
            {
                //Debug.Log(serializer.Deserialize(stream) as ConfigScene);
                return serializer.Deserialize(stream) as ConfigScene;
            }
        }
        catch (Exception e)
        {
            UnityEngine.Debug.LogError("Exception loading config file: " + e);

            return null;
        }
    }
}

The problem is with connectors. 问题出在连接器上。 I think I didn't make it properly. 我认为我做得不好。 So I can't get any data into this Connectors objects. 因此,我无法将任何数据放入此Connector对象。 Do you know maybe how to fix that? 你知道怎么解决吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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