c# XMLReader 在使用 ReadElementContentAs 后跳过节点 [英] c# XMLReader skips nodes after using ReadElementContentAs

查看:27
本文介绍了c# XMLReader 在使用 ReadElementContentAs 后跳过节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析 XML 文件并从元素中提取数据.问题是每次我使用 ReadElementContentAsX 时,阅读器都会跳过下一个元素.我不知道这是为什么.我错过了什么?

I am trying to parse an XML file and extract data from elements. The problem is that every time I use ReadElementContentAsX, the reader skips the next element. I don't know why is that. What am I missing?

while (reader.Read() && fileValid)
{
    if (reader.IsStartElement())
    {
        Console.WriteLine(reader.Name);
        switch (reader.Name)
        {
            case "ID": if (reader.ReadElementContentAsString() != ID)
                {
                    fileValid = false;
                } break;
            case "Size":
                if (reader.ReadElementContentAsInt() != EEPROM_SIZE)
                {
                    fileValid = false;
                }
                break;
            case "Data": if (reader.ReadElementContentAsBase64(eeprom_primary, 0, EEPROM_SIZE) != EEPROM_SIZE)
                {
                    fileValid = false;
                }
                break;
            default:
                break;
        }
    }
}

XML结构如下:<代码>-父节点--ID:字符串--日期:时间日期--SoftwareVersionMajor:int--SoftwareVersionMinor:int--大小:整数--数据:encodedBase64

因此,在我的情况下,我读取元素 ID、大小的元素内容.它将跳过元素日期和数据.我检查了我是否删除了 readElementContent 因为它不会跳过下一个节点

So in my case i read element content for element ID, Size. It will skip element Date and Data. I checked if i remove the readElementContentAs it will not skip the next node

推荐答案

来自 MSND (ReadElementContentAs):

From MSND (ReadElementContentAs):

此方法读取开始标签、元素的内容,并将阅读器移过结束元素标签."

该方法旨在跳到您的下一个元素.

The method is designed to skip to your next element.

你可以用 XmlDocument 试试:

You could try it with XmlDocument:

  XmlDocument xmlDoc = new XmlDocument();
  loadXML(xmlDoc, "inputfile.xml");

然后您可以轻松地使用 Xpath 表达式和每个循环处理 Xml 文件:

And then you can easily process through the Xml file with Xpath expressions and for each loops:

  foreach (XmlNode node in xmlDoc.SelectNodes("/src"))
  {
    // do anything with node
  }

这篇关于c# XMLReader 在使用 ReadElementContentAs 后跳过节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆