- Home /
Proper way to read an XML document
I have an XML file:
For some reason the code is all messed up even though it shows up right in the preview... Link: https://gyazo.com/d9a050f35a553dfe7718a7323e01bdb0
<u1 id="1"> <name>Damage over time</name> <desc>This is an upgrade Damage over time</desc> </u1> <u2 id="2"> <name>Double Damage</name> <desc>This is an upgrade Double damage</desc> </u2> <u3 id="3"> <name>Slow Regen</name> <desc>This is an upgrade Slow Regeneration</desc> </u3> <u4 id="4"> <name>Critical Chance</name> <desc>This is an upgrade Crit Chance</desc> </u4>
and after a lot of pain I am using this code to retrieve the information
using (XmlReader xml = XmlReader.Create(Application.dataPath + Path.DirectorySeparatorChar + "Resources" + Path.DirectorySeparatorChar + "UpgradeDesc.xml")) {
while (xml.Read()) {
if (xml.NodeType == XmlNodeType.Element) {
if (xml.GetAttribute("id") == upgrade.ToString()) {
using (XmlReader inner = xml.ReadSubtree()) {
bool foundDesc = false;
bool foundName = false;
string[] upgradeInfo = new string[3];
while (inner.Read()) {
if (foundName) {
upgradeInfo[0] = inner.Value;
}
if (foundDesc) {
upgradeInfo[1] = inner.Value;
upgradeInfo[2] = "info not from the XML here"; return upgradeInfo;
}
if (inner.LocalName == "name" && string.IsNullOrEmpty(upgradeInfo[0])) {
foundName = true;
}
else {
foundName = false;
}
if (inner.LocalName == "desc" && string.IsNullOrEmpty(upgradeInfo[1])) {
foundDesc = true;
}
else {
foundDesc = false;
}
}
}
}
}
}
throw new System.Exception("No Upgrade of type " + (Upgrade.Upgrades)upgrade + " found!");
}
While this works, I cant imagine this is the right way. How can I improve/optimize it ?
Thanks Majk-
If you want to have a laugh/feel sad, look at the revisions for this topic...
Your answer
![](https://koobas.hobune.stream/wayback/20220612132746im_/https://answers.unity.com/themes/thub/images/avi.jpg)