c# - 使用 XmlTextReader

标签 c# xml web-services xmltextreader

我是一名初级程序员,从 C# 和 Web 服务开始。

在我的网络服务的 Service.cs 文件中,我创建了一个 ReadXMLFile() 方法,我试图在其中读取现有的 XML 文件,从中获取数据它并将其放置到我在 IService.cs 文件中创建的相应属性 (DataMembers)。

我的问题是我的代码基本上什么也没做。我试过寻找这方面的网站和教程,但实际上并没有太多,尤其是对于像我这样的初学者。任何人都知道我应该怎么做,因为到目前为止我一直在尝试的显然是错误的。

下面是我的 ReadXMLFile() 方法。

void ReadXMLFile()
{
    XmlTextReader reader = new XmlTextReader("ClassRoll.xml");
    reader.Read();
    while (reader.Read())
    {
        if (reader.Name == "id")
        {
            id = reader.ReadString();
        }
        else if (reader.Name == "firstname")
        {
            link = reader.ReadString();
        }
        else if (reader.Name == "lastname")
        {
            description = reader.ReadString();
        }
        else if (reader.Name == "count")
        {
            description = reader.ReadString();
        }
        else if (reader.Name == "testscore")
        {
            description = reader.ReadString();
        }
    }
}

这是我的 xml 文件的示例

<classroll>
  <student>
    <id>101010</id>
    <lastname>Smith</lastname>
    <firstname>Joe</firstname>
    <testscores count="5">
      <score>65</score>
      <score>77</score>
      <score>67</score>
      <score>64</score>
      <score>80</score>
    </testscores>
  </student>
</classroll>

最佳答案

您的 while 循环中可能缺少 IsStartElement() 条件:

while (reader.Read())
{
    if (reader.IsStartElement())
    {
       if (reader.Name == "id")
       {
           id = reader.ReadString();
       }
...
}

此外,使用 XPath 会更容易或 LINQ to XML读取您的 XML,当然这取决于文件。以下是一些示例:XPathLINQ .

编辑:查看 XML 文件详细信息后

您应该更新您的逻辑以跟踪当前的学生 及其测试分数。另外,请注意 count 是一个属性。它很快就会变得困惑,我建议你看看上面提到的示例。

关于c# - 使用 XmlTextReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10150785/

相关文章:

c# - 访问 Active Directory 所需的权限?

java - GAEJ : loading external XML

具有枚举和联合的 xml 简单类型

Java/XML请求问题

php - 独特的 key 生成

java - 如何为 JAX-WS Web 服务客户端设置超时?

c# - 使用 WriteFileAsync 附加到文件

c# - unity c#中如何获取点击次数

c# - 如何解析字符串以匹配 C# 中的模式

java - 项目构建错误 : Non-parseable POM/pom. xml : entity reference name can not contain character =' (position: START_TAG seen . ..)