Reputation: 3197
I'm trying to read the following XML file:
<?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>
My code looks like this:
XmlReader reader = XmlReader.Create("data.xml");
reader.ReadStartElement("recipe");
reader.ReadStartElement("name");
String content = reader.ReadElementContentAsString("name", "");´
On the last line it throws an exception:
An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
Additional information: 'Text' is an invalid XmlNodeType. Line 3, position 9.
Why is 'Text' an invalid node type? ReadElementContentAsString sounds like it could easily return the 'Text' as a string.
Upvotes: 2
Views: 5737
Reputation: 18013
The ReadElementContentAsString
reads the element AND its content together. So either you should not consume the <name>
node, or use just ReadContentAsString
instead.
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", "");
Upvotes: 2