使用 ReadElementContentAsString 读取时,XmlReader 'Text' 是无效的 XmlNodeType
XmlReader 'Text' is an invalid XmlNodeType when read with ReadElementContentAsString
我正在尝试阅读以下 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", "");´
最后一行抛出异常:
An unhandled exception of type 'System.Xml.XmlException' occurred in
System.Xml.dll
Additional information: 'Text' is an invalid XmlNodeType. Line 3,
position 9.
为什么 'Text' 是无效的节点类型? ReadElementContentAsString 听起来很容易 return 'Text' 作为字符串。
ReadElementContentAsString
一起读取元素及其内容。因此,您要么不使用 <name>
节点,要么只使用 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", "");
我正在尝试阅读以下 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", "");´
最后一行抛出异常:
An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
Additional information: 'Text' is an invalid XmlNodeType. Line 3, position 9.
为什么 'Text' 是无效的节点类型? ReadElementContentAsString 听起来很容易 return 'Text' 作为字符串。
ReadElementContentAsString
一起读取元素及其内容。因此,您要么不使用 <name>
节点,要么只使用 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", "");