Tengo dificultades para realizar esta tarea aparentemente simple. Quiero cargar archivos XML con la misma facilidad para cargar elementos artísticos:XNA: ¿La mejor manera de cargar y leer un archivo XML?
content = new ContentManager(Services);
content.RootDirectory = "Content";
Texture2d background = content.Load<Texture2D>("images\\ice");
No sé cómo hacerlo. Este tutorial parece útil, pero ¿cómo obtengo una instancia de StorageDevice
?
tengo algo de trabajo, pero se siente muy hacky:
public IDictionary<string, string> Get(string typeName)
{
IDictionary<String, String> result = new Dictionary<String, String>();
xmlReader.Read(); // get past the XML declaration
string element = null;
string text = null;
while (xmlReader.Read())
{
switch (xmlReader.NodeType)
{
case XmlNodeType.Element:
element = xmlReader.Name;
break;
case XmlNodeType.Text:
text = xmlReader.Value;
break;
}
if (text != null && element != null)
{
result[element] = text;
text = null;
element = null;
}
}
return result;
}
aplico esto a la siguiente archivo XML:
<?xml version="1.0" encoding="utf-8" ?>
<zombies>
<zombie>
<health>100</health>
<positionX>23</positionX>
<positionY>12</positionY>
<speed>2</speed>
</zombie>
</zombies>
y es capaz de pasar esta prueba de unidad:
internal virtual IPersistentState CreateIPersistentState(string fullpath)
{
IPersistentState target = new ReadWriteXML(File.Open(fullpath, FileMode.Open));
return target;
}
/// <summary>
///A test for Get with one zombie.
///</summary>
//[TestMethod()]
public void SimpleGetTest()
{
string fullPath = "C:\\pathTo\\Data\\SavedZombies.xml";
IPersistentState target = CreateIPersistentState(fullPath);
string typeName = "zombie";
IDictionary<string, string> expected = new Dictionary<string, string>();
expected["health"] = "100";
expected["positionX"] = "23";
expected["positionY"] = "12";
expected["speed"] = "2";
IDictionary<string, string> actual = target.Get(typeName);
foreach (KeyValuePair<string, string> entry in expected)
{
Assert.AreEqual(entry.Value, expected[entry.Key]);
}
}
Desventajas del enfoque actual: la carga de archivos se realiza mal y las claves de los valores coinciden como si fuera mucho más esfuerzo de lo necesario. Además, sospecho que este enfoque se derrumbaría con más de una entrada en el XML.
No me puedo imaginar que esta sea la implementación óptima.
ACTUALIZACIÓN: Siguiendo el consejo de @Peter Lillevold, he cambiado esto un poco:
public IDictionary<string, string> Get(string typeName)
{
IDictionary<String, String> result = new Dictionary<String, String>();
IEnumerable<XElement> zombieValues = root.Element(@typeName).Elements();
//result["health"] = zombie.Element("health").ToString();
IDictionary<string, XElement> nameToElement = zombieValues.ToDictionary(element => element.Name.ToString());
foreach (KeyValuePair<string, XElement> entry in nameToElement)
{
result[entry.Key] = entry.Value.FirstNode.ToString();
}
return result;
}
public ReadWriteXML(string uri)
{
root = XElement.Load(uri);
}
internal virtual IPersistentState CreateIPersistentState(string fullpath)
{
return new ReadWriteXML(fullpath);
}
/// <summary>
///A test for Get with one zombie.
///</summary>
[TestMethod()]
public void SimpleGetTest()
{
IPersistentState target = CreateIPersistentState("../../../path/Data/SavedZombies.xml");
string typeName = "zombie";
IDictionary<string, string> expected = new Dictionary<string, string>();
expected["health"] = "100";
expected["positionX"] = "23";
expected["positionY"] = "12";
expected["speed"] = "2";
IDictionary<string, string> actual = target.Get(typeName);
foreach (KeyValuePair<string, string> entry in expected)
{
Assert.AreEqual(entry.Value, actual[entry.Key]);
}
}
La carga sigue siendo bastante malo, y de alguna manera yo no era capaz de conseguir el uno línea ToDictionary
para trabajar con esas dos lambdas. Tuve que recurrir a ese ciclo foreach. ¿Qué estoy haciendo mal allí?
Tiene un error tipográfico allí. El @ de mi muestra solo se puede usar con literales de cadena, no con variables de cadena o parámetros. –
Te das cuenta de que el canal de contenido XNA YA admite archivos XML, ¿no? Entonces, literalmente puede usar la misma sintaxis que usa para cargar archivos de arte para cargar archivos XML. –