我对编程和Unity还是很陌生,希望有人可以帮助我找到解决方案。
我有一个包含以下数据的XML文件。我想一次显示一个团队的统计信息,然后当用户单击一个按钮时,我希望脚本循环到XML文件中的下一个团队节点并显示该团队的信息。任何帮助将不胜感激!
<roster>
<team>
<id>0</id>
<teamname>Atlanta Seagulls</teamname>
<overall>90</overall>
<offense>74</offense>
<defense>98</defense>
</team>
<team>
<id>1</id>
<teamname>Minnesota Trees</teamname>
<overall>68</overall>
<offense>58</offense>
<defense>73</defense>
</team>
<team>
<id>2</id>
<teamname>Denver Mountains</teamname>
<overall>50</overall>
<offense>39</offense>
<defense>74</defense>
</team>
这是我的C#脚本的全部内容。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Xml;
using UnityEngine.UI;
using System;
using System.Text;
using System.Xml;
public class LoadXML : MonoBehaviour {
public TextAsset xmlRawFile;
public Text uiText;
public int nodeCount;
public int index;
public int teamId;
public Text teamIdTest;
// Use this for initialization
void Start () {
string data = xmlRawFile.text;
parseXmlFile (data);
}
void parseXmlFile(string xmlData)
{
string totalVal = "";
XmlDocument xmlDoc = new XmlDocument ();
xmlDoc.Load (new StringReader (xmlData));
string xmlPathPattern = "//roster/team";
XmlNodeList myNodeList = xmlDoc.SelectNodes (xmlPathPattern);
nodeCount = myNodeList.Count;
for (int i = 0; i < nodeCount; i++)
{
if (i == index)
{
foreach (XmlNode node in myNodeList)
{
XmlNode id = node.FirstChild;
XmlNode teamname = id.NextSibling;
XmlNode overall = teamname.NextSibling;
XmlNode offense = overall.NextSibling;
XmlNode defense = offense.NextSibling;
teamIdTest.text = id.InnerXml;
teamId = Int32.Parse (id.InnerXml);
if (teamId == i)
{
totalVal = " Team Name: " + teamname.InnerXml + "\nOverall: " + overall.InnerXml + "\nOffense : " + offense.InnerXml + "\nNodes : " + nodeCount + "\n\n";
uiText.text = totalVal;
}
}
}
}
}
public void Swap()
{
if (index < nodeCount - 1) {
index++;
} else {
index = 0;
}
}
}
答案 0 :(得分:0)
例如,您可以读取文件并将每个团队值存储在XmlNodes数组中。该代码可以将节点列表转换为数组:
XmlNode[] nodeArray = myNodeList.Cast<XmlNode>().ToArray();
然后,当用户单击按钮时,您将从数组中选择下一个项目并执行操作:
public void SwapNext()
{
//nodeArray and currentNodeIndex should be private class variables so you can reach them from all class functions
currentNodeIndex += 1 ;
node = nodeArray[currentNodeIndex];
XmlNode id = node.FirstChild;
XmlNode teamname = id.NextSibling;
XmlNode overall = teamname.NextSibling;
XmlNode offense = overall.NextSibling;
XmlNode defense = offense.NextSibling;
teamIdTest.text = id.InnerXml;
teamId = Int32.Parse (id.InnerXml);
totalVal = $"Team Name: {teamname.InnerXml} Overall {overall.InnerXml} Offense : {offense.InnerXml} Nodes {nodeCount}";
uiText.text = totalVal;
您也可以像现在一样立即解析整个文件,并将team值存储为某个类的对象,例如Team类,然后使用对象Team数组而不是XmlNode。