【发布时间】:2014-10-12 13:49:42
【问题描述】:
我有这个 xml(为了举例,它被修剪了)
<?xml version="1.0" encoding="utf-8"?>
<levels>
<level><!-- level 1 ! -->
<name>Level 1</name>
<title>Title 01</title>
<crystal01>false</crystal01>
<crystal02>false</crystal03>
<crystal02label>Label 1</crystal03label>
<crystal03>false</crystal04>
</level>
<level><!-- level 2 ! -->
<name>Level 2</name>
<title>Title 02</title>
<crystal01>true</crystal01>
<crystal02>true</crystal03>
<crystal02label>Label 2</crystal03label>
<crystal03>false</crystal04>
</level>
</levels>
我使用这个脚本将数据加载到一些变量中
public class LoadXmlData : MonoBehaviour // the Class
{
public int actualLevel = 1;
static int LevelMaxNumber;
static int WaipointCounter = 0;
public static string lvlname = "";
public static string lvltitle = "";
public static string crystal01 = "";
public static string crystal02 = "";
public static string crystal02label = "";
public static string crystal03 = "";
public TextAsset XMLData;
List<Dictionary<string,string>> levels = new List<Dictionary<string,string>>();
Dictionary<string,string> obj;
void Start()
{ GetLevel();
StartCoroutine(LevelLoadInfo(0.0F));
LevelMaxNumber = levels.Count;
}
public void GetLevel()
{
XmlDocument xmlDoc = new XmlDocument(); // xmlDoc is the new xml document.
xmlDoc.LoadXml(XMLData.text); // load the file.
XmlNodeList levelsList = xmlDoc.GetElementsByTagName("level"); // array of the level nodes.
foreach (XmlNode levelInfo in levelsList)
{
XmlNodeList levelcontent = levelInfo.ChildNodes;
obj = new Dictionary<string,string>();
foreach (XmlNode levelsItens in levelcontent) // levels itens nodes.
{
if(levelsItens.Name == "name")
{
obj.Add("name",levelsItens.InnerText); // put this in the dictionary.
}
if(levelsItens.Name == "title")
{
obj.Add("title",levelsItens.InnerText); // put this in the dictionary.
}
if(levelsItens.Name == "crystal01")
{
obj.Add("crystal01",levelsItens.InnerText); // put this in the dictionary.
}
if(levelsItens.Name == "crystal02")
{
obj.Add("crystal02",levelsItens.InnerText); // put this in the dictionary.
}
if(levelsItens.Name == "crystal02label")
{
obj.Add("crystal02label",levelsItens.InnerText); // put this in the dictionary.
}
if(levelsItens.Name == "crystal03")
{
obj.Add("crystal03",levelsItens.InnerText); // put this in the dictionary.
}
}
levels.Add(obj); // add whole obj dictionary in the levels[].
}
}
IEnumerator LevelLoadInfo(float Wait)
{
levels[actualLevel-1].TryGetValue("name",out lvlname);
levels[actualLevel-1].TryGetValue("title",out lvltitle);
levels[actualLevel-1].TryGetValue("crystal01",out crystal01);
levels[actualLevel-1].TryGetValue("crystal02",out crystal02);
levels[actualLevel-1].TryGetValue("crystal02label",out crystal02label);
levels[actualLevel-1].TryGetValue("crystal03",out crystal03);
yield return new WaitForSeconds(Wait);
}
void Update()
{
}
}
一切正常,但我真的努力了几天来创建一个访问某个节点的函数,覆盖它的数据并保存 xml,我知道这有点简单,但我不明白(我是 3d艺术家,我从去年开始编程,所以,还在学习阶段),例如,我如何在级别 2 中编辑“水晶02”值并保存 xml? 提前致谢!
【问题讨论】:
-
我强烈推荐使用 Linq to XML。
标签: c# xml xmldocument