【问题标题】:When using XmlReader, the HasValue property returns False! Why?使用 XmlReader 时,HasValue 属性返回 False!为什么?
【发布时间】:2016-02-27 22:43:11
【问题描述】:

这是我的 XML 文件...

<application>
  <name>My Application</name>
  <ou/>
  <area/>
  <created time="na"/>
  <id closed="no"/>
  <description>My App Description</description>
  <version type="beta">1.0</version>
  <modified>02/24/2016</modified>
  <files>
    <file>
      <name>my_app.exe</name>
      <size type="bytes" complete="yes" updated="no">225684</size>
      <description>Main GUI for Application.</description>
      <version>1.5</version>
      <modified>02/24/2016</modified>
    </file>
    <file>
      <name>testfile.dll</name>
      <size type="bytes" complete="yes" updated="no">1024</size>
      <description>Support DLL for Application.</description>
      <version>1.1</version>
      <modified>02/23/2016</modified>
    </file>
  </files>
</application>

我用它来读取我的 XML 文件...

using (XmlReader reader = XmlReader.Create("my_xml_file.xml"))
{
  while (!reader.EOF)
  {
    switch (reader.NodeType)
    {
      case XmlNodeType.Element:
        if (reader.HasValue)
          Debug.WriteLine("Node Value:" + reader.ReadString());
        break;
    }
  }
}

我不知道为什么,但出于某种原因,我的 reader.HasValue 属性始终是 FALSE。我认为当该节点上有一个值时,该属性应该是TRUE。如果我每次都打电话给reader.ReadString(),它会推进读者并搞砸我正在尝试做的事情。我错了吗?

【问题讨论】:

  • @zx485 备案,没有拼写错误。 :P 看到我无法拼写来挽救我的生命,我想我会为自己的成就感到自豪并吹嘘它。 ;)
  • 说得好阿沃。我尊重你诚实的批评。我不得不承认我不是以英语为母语的人。尽管如此,让我解释一下我的主要主要目标:我不是来责备你或其他任何人的拼写或语法错误。我只是想通过删除误导性的单词组合和突出显示关键字来提高其他人的可读性。这与 SO 团队鼓励的社区标准完全一致。提高帖子的可读性可以减轻理解,这对读者(可能会回答问题的人)是有益的。
  • 100% 同意!你能满足我的日常语法需求吗?
  • 不!我只是满足 SO 社区的语法需求;-)

标签: c# xml .net-4.0


【解决方案1】:

元素本身没有值(在你的意思上 - 它不能) - 元素中的“文本”节点有。

      case XmlNodeType.Text:
      Console.Write(reader.Value);
      break;

【讨论】:

  • 嗯,我想这是有道理的......有没有办法在调用 ReadString() 之前判断是否有值?
  • 是的 - 你最初的想法 - reader.HasValue - 但是在文本节点而不是元素上调用它(即当你在文本节点时在阅读器上调用它)
猜你喜欢
  • 2021-09-23
  • 2019-12-31
  • 2020-10-07
  • 2016-08-23
  • 2013-09-18
  • 2014-06-28
  • 2011-05-22
  • 2014-11-17
  • 2014-03-11
相关资源
最近更新 更多