【问题标题】:XmlReader 'Text' is an invalid XmlNodeType when read with ReadElementContentAsString使用 ReadElementContentAsString 读取时,XmlReader 'Text' 是无效的 XmlNodeType
【发布时间】:2015-11-02 12:19:46
【问题描述】:

我正在尝试读取以下 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<recipe>
  <name>5 SE</name>
  <timecreated>02.11.2015 13:13:36</timecreated>
  <min>90</min>
  <max>130</max>
  <range>40</range>
  <avg>110</avg>
  <stddev>40</stddev>
</recipe>

我的代码如下所示:

XmlReader reader = XmlReader.Create("data.xml");
reader.ReadStartElement("recipe");
reader.ReadStartElement("name");
String content = reader.ReadElementContentAsString("name", "");´

在最后一行抛出异常:

“System.Xml.XmlException”类型的未处理异常发生在 System.Xml.dll

附加信息:“文本”是无效的 XmlNodeType。 3号线, 位置 9。

为什么“文本”是无效的节点类型? ReadElementContentAsString 听起来它可以轻松地将“文本”作为字符串返回。

【问题讨论】:

  • 您已经使用了标签名称,所以您需要做的就是获取值:string content = reader.Value;

标签: c# .net xml xmlreader


【解决方案1】:

ReadElementContentAsString 一起读取元素及其内容。因此,要么您不应该使用 &lt;name&gt; 节点,要么只使用 ReadContentAsString

XmlReader reader = XmlReader.Create("data.xml", new XmlReaderSettings { IgnoreWhitespace = true });
reader.ReadStartElement("recipe");
// reader.ReadStartElement("name"); - now you will be at the <name> element instead of "5 SE" text
String content = reader.ReadElementContentAsString("name", "");

【讨论】:

  • 好的。我之前也试过。它给了我另一个 XmlException 作为对 ReadElementContentAsString() 的调用:'Whitespace' is an invalid XmlNodeType
  • 那么您应该忽略不重要的空格。请参阅我修改后的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 2013-02-19
  • 1970-01-01
  • 2012-10-20
  • 2010-11-07
相关资源
最近更新 更多