- Home /
Question by
Ratboy601 · Jan 03, 2016 at 08:59 AM ·
xmlruntime-error
Reading Xml files, InvalidCastException
Hi, I know there's lots of questions out there about invalid cast exceptions, but I couldn't find any that are cluing me in enough on my problem. I got this script from the forums for adding multiple language support, and its a bit more advanced than my current skill level. The line from SetLanguage()
var xmlItem = (XmlElement)elemEnum.Current;
is giving me the InvalidCastException runtime error when I call the function from another script like this:
langClass.setLanguage (Path.Combine (Application.dataPath, currentLevel + currentLanguage + ".xml"), currentLanguage);
Here's the whole script for your reference. If I can post anything else to help, please let me know.
using System;
using System.Collections;
using System.IO;
using System.Xml;
using UnityEngine;
public class Lang
{
private Hashtable Strings;
public Lang ( string path, string language, bool web) {
if (!web) {
setLanguage(path, language);
} else {
setLanguageWeb(path, language);
}
}
public void setLanguage ( string path, string language) {
var xml = new XmlDocument();
xml.Load(path);
Strings = new Hashtable();
var element = xml.DocumentElement[language];
if (element != null) {
var elemEnum = element.GetEnumerator();
while (elemEnum.MoveNext()) {
var xmlItem = (XmlElement)elemEnum.Current;
Strings.Add(xmlItem.GetAttribute("name"), xmlItem.InnerText);
}
} else {
Debug.LogError("The specified language does not exist: " + language);
}
}
public void setLanguageWeb ( string xmlText, string language) {
var xml = new XmlDocument();
xml.Load(new StringReader(xmlText));
Strings = new Hashtable();
var element = xml.DocumentElement[language];
if (element != null) {
var elemEnum = element.GetEnumerator();
while (elemEnum.MoveNext()) {
var xmlItem = (XmlElement)elemEnum.Current;
Strings.Add(xmlItem.GetAttribute("name"), xmlItem.InnerText);
}
} else {
Debug.LogError("The specified language does not exist: " + language);
}
}
/*
Access strings in the currently selected language by supplying this getString function with
the name identifier for the string used in the XML resource.
Example:
XML file:
<languages>
<English>
<string name="app_name">Unity Multiple Language Support</string>
<string name="description">This script provides convenient multiple language support.</string>
</English>
<French>
<string name="app_name">Unité Langue Soutien Multiple</string>
<string name="description">Ce script fournit un soutien multilingue pratique.</string>
</French>
</languages>
JavaScript:
var appName : String = langClass.getString("app_name");
*/
public string getString (string name) {
if (!Strings.ContainsKey(name)) {
Debug.LogError("The specified string does not exist: " + name);
return "";
}
return (string)Strings[name];
}
}
Comment