好的,我有这个 XML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<Item>
<Name>Iron Repeater</Name>
<AutoReuse>true</AutoReuse>
<UseAnimation>19</UseAnimation>
<UseTime>19</UseTime>
<Width>50</Width>
<Height>18</Height>
<Shoot>1</Shoot>
<UseAmmo>1</UseAmmo>
<UseSound>5</UseSound>
<Damage>39</Damage>
<ShootSpeed>11</ShootSpeed>
<NoMelee>true</NoMelee>
<Value>200000</Value>
<Ranged>true</Ranged>
<Rarity>4</Rarity>
<Knockback>2.5</Knockback>
<CraftStack>1</CraftStack>
<CraftItem1>Wood</CraftItem1>
<CraftValue1>1</CraftValue1>
<CraftTile1>18</CraftTile1>
<FinishCrafting/>
</Item>
它的读法与此类似:
foreach (string s in API.itemFiles)
{
using (XmlReader reader = XmlReader.Create(s))
{
string aTile;
string aStack;
string item;
string iName;
int tile;
int stack;
int iStack;
reader.MoveToContent();
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.IsStartElement())
{
switch (reader.Name)
{
//Le cases here
}
}
}
}
}
}
API.itemFiles 是:
public static string[] itemFiles = Directory.GetFiles(itemSave, "*.xml");
每当我尝试以这种方式读取 XML 文件时,它似乎都没有将元素内容(我执行 readElementContentAsXX();)解析为变量或其他内容,但它似乎确实找到了正确的元素。
我是不是做错了什么?有什么我可以改进的吗?如果还有其他读取 XML 的方法(它将计划有大量 XML 文件;我需要它来提高效率),请说!
谢谢!
最佳答案
我找不到您的解决方案有任何明显错误。当我测试它时,打开 reader.Name
有效。
我建议使用一些更传统的 XML 格式。您可以将这些元素移动到子元素中,而不是编号元素:
<Item>
...
<Stacks>
<Stack>
<Item>Wood</Item>
<Value>1</Value>
<Tile>18</Tile>
</Stack>
</Stacks>
</Item>
然后您可以使用 XML 对象序列化来解析文件。这样就不容易出错。
public class Item
{
public string Name;
public bool AutoReuse;
public int UseAnimation;
public int UseTime;
public int Width;
public int Height;
public int Shoot;
public int UseAmmo;
public int UseSound;
public int Damage;
public int ShootSpeed;
public bool NoMelee;
public int Value;
public bool Ranged;
public int Rarity;
public decimal Knockback;
public List<Stack> Stacks;
}
public class Stack
{
public string Item;
public int Value;
public int Tile;
}
XmlSerializer x = new XmlSerializer(typeof(Item));
var item = (Item) x.Deserialize(steam);
关于C# - 有效使用 XmlReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9756945/