[Q] Writing in an XML File Problem

Robby Light

Member
May 31, 2010
37
1
0
www.thepagedot.de
Hey Guys!

I'm sitting in front of an XML-Problem for five days now and really don't know what's to do. Expect of asking you.

I want to write a small shopping list application that manages the data in an XML-File looking like that:

Code:
<?xml version="1.0" encoding="utf-8" ?>
<Items>
  <Item>
    <Name>Bananas</Name>
    <Store>supermarket</Store>
    <Repeat>true</Repeat>
  </Item>
  <Item>
    <Name>LG E900 Optimus 7</Name>
    <Store>superhandy</Store> 
    <Repeat>false</Repeat>
  </Item>
(...)
I have a ListBox called ItemShowcase that I fill with instances of my ShowCaseEntry-Class
Reading Data from the FIle works perfectly with this code:
Code:
private void updateItemList()
        {
            // load XML-File
            var items = XElement.Load("MissingItems.xml");

            foreach (var a in items.Elements())
            {
                ShowCaseEntry sce = new ShowCaseEntry(a.Element("Name").Value, "Store: " + a.Element("Store").Value, false);
                ItemShowcase.Items.Add(sce);
            }
        }
No Problem until here.
But now I want to add a new Iem to my XML-File.
I have 2 Textfields in what I ask for the Item-Name and Store-Name. Repeat is always true.
I tried that:
Code:
public void addXMLItem(String name, String store, Boolean repeat)
        {

            // XML-Datei Laden
            var items = XDocument.Load("MissingItems.xml");

            // neues Item erstellen
            XElement newItem = new XElement("Item",
                 new XElement("Name", name),
                 new XElement("Store", store),
                 new XElement("Repeat", repeat) );
            
            // Hinzufügen und spreichern            
            items.Root.Add(newItem);

            FileStream F = new FileStream("MissingItems.xml", FileMode.Open);
            items.Save(F);
        }
The last line give me the following Error:
Attempt to access the method failed: System.IO.FileStream..ctor(System.String, System.IO.FileMode)

Is anyone here who would help me?
You would save my weekend!

Thank you so much!

Best wishes and greets

Robby
 

Ren13B

Senior Member
Oct 10, 2007
251
18
0
Try something like this:
Code:
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream;

isoStream = new IsolatedStorageFileStream("MissingItems.xml", FileMode.Create, FileAccess.Write, isoStore);

//Add your xml items here.

xml.Save(isoStream);
isoStream.Close();
 

Robby Light

Member
May 31, 2010
37
1
0
www.thepagedot.de
First of all thanks for your answer.

Unfortunately I don't really know how to add the XML-Items.

Like this?
Code:
public void addXMLItem(String name, String store, Boolean repeat)
        {
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream isoStream;

            isoStream = new IsolatedStorageFileStream("MissingItems.xml", FileMode.Create, FileAccess.Write, isoStore);

            //Add your xml items here.
            
            var items = XDocument.Load("MissingItems.xml");
            XElement newItem = new XElement("Item",
                 new XElement("Name", name),
                 new XElement("Store", store),
                 new XElement("Repeat", repeat));

                 
            items.Root.Add(newItem);

            items.Save(isoStream);
            isoStream.Close();
        }
Another answer would be very nice

Best regards

Robby
 

Ren13B

Senior Member
Oct 10, 2007
251
18
0
I don't have time to test it but hopefully this works for you.

Code:
public void addXMLItem(String name, String store, Boolean repeat)
        {
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream isoStream;

            isoStream = new IsolatedStorageFileStream("MissingItems.xml", FileMode.Create, FileAccess.Write, isoStore);

            //Add your xml items here.
            
            XDocument items = XDocument.Load(isoStream);
            
            items.Element("Items").Add(
                 new XElement("Item",
                 new XElement("Name", name),
                 new XElement("Store", store),
                 new XElement("Repeat", repeat)));

            items.Save(isoStream);
            isoStream.Close();
        }
 

Robby Light

Member
May 31, 2010
37
1
0
www.thepagedot.de
Thank you really much for your engangement, but there is still one problem.
In this line the program throws an XML-Error called "root element is missing":

XDocument items = XDocument.Load(isoStream);


How to explain the Load-Method that "Items" is my root Element?

Greets

Robby
 

Ren13B

Senior Member
Oct 10, 2007
251
18
0
Sorry my code had errors. This is tested and working.
Code:
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream isoStream;

            isoStream = new IsolatedStorageFileStream("MissingItems.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);
            XDocument items = XDocument.Load(isoStream);
            isoStream.Close();

            items.Element("Items").Add(
                 new XElement("Item",
                 new XElement("Name", name),
                 new XElement("Store", store),
                 new XElement("Repeat", repeat.ToString())));


            isoStream = new IsolatedStorageFileStream("MissingItems.xml", FileMode.Create, FileAccess.Write, isoStore);
            items.Save(isoStream);

            isoStream.Close();
That code results in this:
Code:
<?xml version="1.0" encoding="utf-8"?>
<Items>
  <Item>
    <Name>Bananas</Name>
    <Store>supermarket</Store>
    <Repeat>true</Repeat>
  </Item>
  <Item>
    <Name>LG E900 Optimus 7</Name>
    <Store>superhandy</Store>
    <Repeat>false</Repeat>
  </Item>
  <Item>
    <Name>Test Name</Name>
    <Store>Test Store</Store>
    <Repeat>False</Repeat>
  </Item>
</Items>
 
Last edited:

Robby Light

Member
May 31, 2010
37
1
0
www.thepagedot.de
I really, really thank you for your anxiety. Thank you for your time, but I just have one more error.

This line throwes an Isolated Storage Exception called "Operation not permitted on IsolatedStorageFileStream.":

isoStream = new IsolatedStorageFileStream("MissingItems.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);


You would save my week with a short answer!
Thank you so much till yet

Robby
 

Ren13B

Senior Member
Oct 10, 2007
251
18
0
It sounds like the file stream is already open somewhere else. If you are doing any other reads or writes to the file prior to your addxmlitem method you need to close the stream before calling addxmlitem.
 

Robby Light

Member
May 31, 2010
37
1
0
www.thepagedot.de
Not really :(
Sorry, I am sure that I'm annoying but I really need to fix that problem.
My last try to solve ist is to send you the full code:

Code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using System.Xml;
using System.Text;
using System.IO;
using System.IO.IsolatedStorage;


namespace MyShoppingList
{

    public partial class MainPage : PhoneApplicationPage
    {

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            Item[] itemArray = new Item[2];
            CheckBox[] checkBoxArray = new CheckBox[2];


            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);

            updateItemList();
        }


        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }

        /// <summary>
        /// Adds new Item to the XML-File
        /// </summary>
        /// <param name="name">Itemname</param>
        /// <param name="store">Storename</param>
        /// <param name="repeat">Repeat</param>
        public void addXMLItem(String name, String store, Boolean repeat)
        {
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream isoStream;

            isoStream = new IsolatedStorageFileStream("MissingItems.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);
            XDocument items = XDocument.Load(isoStream);
            isoStream.Close();

            items.Element("Items").Add(
                 new XElement("Item",
                 new XElement("Name", name),
                 new XElement("Store", store),
                 new XElement("Repeat", repeat.ToString())));


            isoStream = new IsolatedStorageFileStream("MissingItems.xml", FileMode.Create, FileAccess.Write, isoStore);
            items.Save(isoStream);

            isoStream.Close();
        }

        /// <summary>
        /// Updates Item List
        /// </summary>
        private void updateItemList()
        {
            // XML-Datei Laden
            var items = XElement.Load("MissingItems.xml");

            foreach (var a in items.Elements())
            {
                ShowCaseEntry sce = new ShowCaseEntry(a.Element("Name").Value, "Store: " + a.Element("Store").Value, false);
                ItemShowcase.Items.Add(sce);
            }
        }


        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            addXMLItem(tBoxAddItemName.Text, tBoxAddItemStore.Text, false);
            //updateItemList();
        }
    }
}
Can you find any mistakes?
I'm getting desperate...

Thanks a lot for your engagement!
 

Ren13B

Senior Member
Oct 10, 2007
251
18
0
I'n not really sure why that's happening. The only thing I can think of is XElement.Load() is causing the problem so here's how to use XDocument.Load() instead. I really hope this works for you because I'm out of ideas.

Code:
        private void updateItemList()
        {

            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream isoStream;

            isoStream = new IsolatedStorageFileStream("MissingItems.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);
            XDocument xml = XDocument.Load(isoStream);

            var items = from c in xml.Elements("Items").Elements("Item")
                                     select new {
                                        name = c.Element("Name").Value,
                                        store = c.Element("Store").Value,
                                        repeat = c.Element("Repeat").Value
                                     };

            foreach (var item in items)
            {
               ShowCaseEntry sce = new ShowCaseEntry(item.name, "Store: " + item.store, false);
               ItemShowcase.Items.Add(sce);

            }

            isoStream.Close();
         
        }
 

Robby Light

Member
May 31, 2010
37
1
0
www.thepagedot.de
Same Error on this line:

isoStream = new IsolatedStorageFileStream("MissingItems.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);

Operation not permitted on IsolatedStorageFileStream.
I'm at the end of my motivation :(
I really tried everything, you really tried everything and I cannot find anything helpful to this error message..

Does anyone has an idea?
Does this line works for you?

Big Thanks to Ren13B till yet!
 

Ca5c4d3

Senior Member
Apr 6, 2007
145
11
0
London
If you are accessing the Isolated Storage from within a referenced assembly, you will need to access the IsolatedStorageFile for that assembly :)