C# - 有效使用 XmlReader

标签 c# xml xmlreader

好的,我有这个 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/

相关文章:

c# - 使用 C# (.NET core) 将文件从 linux 复制到 windows 共享

c# - 为什么NEST ElasticClient找不到文档?

php - 使用 XMLReader 在 PHP 中验证 SVG 文件

C# 解析以下 XML,不确定如何

C# XmlWriter - 在 Element 中添加元素

c# - 如何正确地使 String.PadRight() 适应字符串

c# TimeSpan 将分钟转换为小时

java - 如何在没有 XML 文件的情况下使屏幕可滚动?

xml - 使用PowerShell替换嵌套XML中的值

android - xml 中的放大和旋转动画