4 Replies - 4026 Views - Last Post: 01 September 2012 - 03:34 PM Rate Topic: -----

#1 triplesowcow  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 21
  • Joined: 31-August 11

XML reading and writing with XmlWriter and XmlReader.

Posted 01 September 2012 - 12:46 PM

The first problem is with writing. I am trying to iterate through a listbox full of objects and write down their relevant bits and pieces.
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FileStream myStream;
            SaveFileDialog mySave = new SaveFileDialog();
            mySave.Filter = "XML Files (*.xml)|*.xml";
            mySave.FilterIndex = 1;
            mySave.RestoreDirectory = true;
            if (mySave.ShowDialog() == DialogResult.OK)
            {
                if ((myStream = (FileStream)mySave.OpenFile()) != null)
                {
                    XmlWriter myWriter = XmlWriter.Create(myStream);
                    myWriter.WriteStartDocument();
                    myWriter.WriteStartElement("Catalog");

                    for (int index = 0; index > listBox1.Items.Count; index++)
                    {
                        myWriter.WriteStartElement("machineObj");
                        myWriter.WriteStartElement("name");
                        myWriter.WriteString(((MachineObj)listBox1.Items[index]).sName);
                        myWriter.WriteEndElement();
                        myWriter.WriteStartElement("model");
                        myWriter.WriteString(((MachineObj)listBox1.Items[index]).sModel);
                        myWriter.WriteEndElement();
                        myWriter.WriteStartElement("serial");
                        myWriter.WriteString(((MachineObj)listBox1.Items[index]).sSerial);
                        myWriter.WriteEndElement();
                        myWriter.WriteStartElement("information");
                        myWriter.WriteString(((MachineObj)listBox1.Items[index]).sAdditionalInfo);
                        myWriter.WriteEndElement();
                        myWriter.WriteStartElement("manufacturer");
                        myWriter.WriteString(((MachineObj)listBox1.Items[index]).sManufacturer);
                        myWriter.WriteEndElement();
                        myWriter.WriteEndElement();
                    }
                        myWriter.WriteEndElement();
                        myWriter.WriteEndDocument();
                        myWriter.Close();
                }
            }
        }


this produces an Xml document that looks like

<?xml version="1.0" encoding="UTF-8"?>
<Catalog/>


the second problem is with reading.

After writing out an xml document that looks like my desired output from the save button, I tried to load it back into the listbox using
private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FileStream myStream;
            OpenFileDialog myOpen = new OpenFileDialog();
            myOpen.Filter = "XML Files (*.xml)|*.xml";
            myOpen.FilterIndex = 1;
            myOpen.RestoreDirectory = true;
            if (myOpen.ShowDialog() == DialogResult.OK)
            {
                if ((myStream = (FileStream)myOpen.OpenFile()) != null)
                {
                    XmlReader myReader = XmlReader.Create(myStream);

                    while(myReader.ReadToFollowing("machineObj"))
                    {
                        MachineObj xmlMachine = new MachineObj();
                        myReader.ReadToFollowing("name");
                        xmlMachine.sAdditionalInfo = myReader.ReadElementContentAsString();
                        myReader.ReadToFollowing("model");
                        xmlMachine.sModel = myReader.ReadElementContentAsString();
                        myReader.ReadToFollowing("serial");
                        xmlMachine.sSerial = myReader.ReadElementContentAsString();
                        myReader.ReadToFollowing("information");
                        xmlMachine.sAdditionalInfo = myReader.ReadElementContentAsString();
                        myReader.ReadToFollowing("manufacturer");
                        xmlMachine.sManufacturer = myReader.ReadElementContentAsString();
                        listBox1.Items.Add(xmlMachine);
                    }
                    myReader.Close();
                }
            }
        }


I get error message "The ReadElementContentAsString method is not supported on node type None. Line 3, position 59."
and if i remove the while loop and try to read a single object from the xml i get an out of memory exception saying that listbox is full despite listbox1.items.count() still being 0.


Any insight on either of the two problems would be appreciated.

Is This A Good Question/Topic? 0
  • +

Replies To: XML reading and writing with XmlWriter and XmlReader.

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5522
  • View blog
  • Posts: 11,830
  • Joined: 02-June 10

Re: XML reading and writing with XmlWriter and XmlReader.

Posted 01 September 2012 - 12:52 PM

Yikes. Looks like you are trying to micro-manage the entire read/write process. What about just serializing an object to XML and let the serialization class do all that for you? After all, all that read in data has to go into a class anyway right? So just deserialize into a new instance of that class and move on.

Separating data from GUI - PLUS - serializing the data to XML

One of the biggest problems with what you have here is that eveyr time you update the class with a new property you have to update your read/write methods. Might as well be doing .ini files from the 80's.

Serialization just takes and gives an entire object. No changes to methods required when you add a new property.

One of the biggest problems with what you have here is that eveyr time you update the class with a new property you have to update your read/write methods. Might as well be doing .ini files from the 80's.

Serialization just takes and gives an entire object. No changes to methods required when you add a new property.
Was This Post Helpful? 0
  • +
  • -

#3 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3575
  • View blog
  • Posts: 11,116
  • Joined: 05-May 12

Re: XML reading and writing with XmlWriter and XmlReader.

Posted 01 September 2012 - 03:15 PM

View Posttriplesowcow, on 01 September 2012 - 12:46 PM, said:

The first problem is with writing. I am trying to iterate through a listbox full of objects and write down their relevant bits and pieces.
Spoiler

this produces an Xml document that looks like

<?xml version="1.0" encoding="UTF-8"?>
<Catalog/>


You obviously have not even tried to step through your code with a debugger. Take a closer look at your line 16. When will that ever be true?
Was This Post Helpful? 1
  • +
  • -

#4 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5522
  • View blog
  • Posts: 11,830
  • Joined: 02-June 10

Re: XML reading and writing with XmlWriter and XmlReader.

Posted 01 September 2012 - 03:21 PM

Good catch skydiver. The entire concept was just way too wrong for me to even consider looking that closely.

triplesowcow: What this shows us is that you aren't familiar with breakpoints and how to debug your own code. Learning to debug one's own code is an essential skill. Sadly, one that apparently few college courses teach. Silly if you ask me.

Placing breakpoints and walking through the code line by line allows you to actually WATCH it execute.

Visualizing what your code does will let you see why it behaves the way it does.

It would be well worth your time to do the tutorials on FAQ 2. A couple hours learning this skill will save you hundreds of hours of confusion in one project alone.


See FAQ # 2. (Click the SHOW button below)



TOP most asked:
What does this error message mean?
FAQ 2: How do I debug
FAQ 3: How do I make Class1/Form1 talk to Class2/Form2


FAQ (Frequently Asked Questions - Updated July 2012
Spoiler



Was This Post Helpful? 0
  • +
  • -

#5 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3575
  • View blog
  • Posts: 11,116
  • Joined: 05-May 12

Re: XML reading and writing with XmlWriter and XmlReader.

Posted 01 September 2012 - 03:34 PM

I don't know about your listbox issues, but the parsing seems to work correctly for me with a minimal case of:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;

namespace SimpleCSConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            var stringReader = new System.IO.StringReader(
@"<catalog>
    <machineObj>
      <name>Foo1</name>
      <model>Bar1</model>
    </machineObj>
    <machineObj>
      <name>Foo2</name>
      <model>Bar2</model>
    </machineObj>
  </catalog>");
            var reader = new XmlTextReader(stringReader);
            while (reader.ReadToFollowing("machineObj"))
            {
                reader.ReadToFollowing("name");
                Console.WriteLine(reader.ReadElementContentAsString());
                reader.ReadToFollowing("model");
                Console.WriteLine(reader.ReadElementContentAsString());
            }
        }
    }
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1