Writing and reading xml

  • Thread starter Thread starter Gve
  • Start date Start date
G

Gve

Hi,

I'm building an xml message with the XmlWriter class and process this xml
message with the XmlReader class. The message I build looks like:
<parent>
<child>car</child>
<child>bus</child>
<child>plane</child>
</parent>

When I build the message with XmlWriterSettings and set the
XmlWriterSettings .Indent property to true, I'll get the expected results
when I iterate through the message with the XmlReader class. Nevertheless,
when I build the message with setting the XmlWriterSettings .Indent property
to false, the bus value won't show up.

Is this by design or is it a bug? I've tried framework 2.0 and 3.5.

The following code fragment presents the problem:
//==
using System;
using System.IO;
using System.Xml;

namespace ConsoleApplication1 {
class Program {

static void Main(string[] args) {
WriteAndReadXml(true);
WriteAndReadXml(false);
}

static void WriteAndReadXml(bool indent) {
Console.WriteLine("-Indent: {0}", indent);
using(Stream s = new MemoryStream()) {
WriteXml(s, indent);
s.Position = 0;
ReadXml(s);
}
Console.WriteLine("\r\n");
}

static void WriteXml(Stream output, bool indent) {
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = indent;
using(XmlWriter writer = XmlWriter.Create(output, settings)) {
writer.WriteStartDocument();
writer.WriteStartElement("parent");
foreach(string value in new string[] { "car", "bus", "plane" }) {
writer.WriteStartElement("child");
writer.WriteValue(value);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
}

static void ReadXml(Stream input) {
using (XmlReader reader = XmlReader.Create(input))
while(reader.ReadToFollowing("child"))
Console.WriteLine(reader.ReadElementContentAsString());
}

}
}
//==


Thanx
Regards
 
Gve said:
I'm building an xml message with the XmlWriter class and process this xml
message with the XmlReader class. The message I build looks like:
<parent>
<child>car</child>
<child>bus</child>
<child>plane</child>
</parent>

When I build the message with XmlWriterSettings and set the
XmlWriterSettings .Indent property to true, I'll get the expected results
when I iterate through the message with the XmlReader class. Nevertheless,
when I build the message with setting the XmlWriterSettings .Indent property
to false, the bus value won't show up.

Is this by design or is it a bug? I've tried framework 2.0 and 3.5.

It's not a bug - it's due to how you're reading it. When you've got
indenting, there's a text node between the two elements. When you've
not got indenting, there's just the element and then the next element.

ReadElementContentAsString moves to *after* the element, leaving the
reader on the text node (with indenting) or the next element (without
indenting).

You then call ReadToFollowing which looks at elements *after* the
current one - so if you're already on the element you actually want,
it's going to skip it.
 
Back
Top