简体   繁体   中英

How can I save to XML?

I'm currently making a new WP7 application that should enable users to fill in two textboxes, click a button, and make the content become a part of a .XML file.

At this point, I'm using the following code:

string ItemName = ItemNameBox.Text;
string ItemAmount= ItemAmountBox.Text;

string xmlString = "<Items><Name>"+ItemName+"</Name></Item>";
XDocument document = XDocument.Parse(xmlString);
document.Root.Add(new XElement("Amount", ItemAmount));
string newxmlString = document.ToString();

MessageBox.Show(newxmlString);

Now, when I click the button (as this is within an onclick button event), the MessageBox shows me that the output is correct XML-wise.

However, how do I get this into an existing XML schema, which should be able to contain quite a few rows (to-do/shopping list, for example)?

This is a generic saver I have written for windows phone.

public static void SaveDataToIsolatedStorage(string filePath, FileMode fileMode, XDocument xDoc)
{
    using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
    using (IsolatedStorageFileStream location = new IsolatedStorageFileStream(filePath, fileMode, storage))
    {
        System.IO.StreamWriter file = new System.IO.StreamWriter(location);
        xDoc.Save(file);
    }
}

If you want to add multiple "rows" of data you could do it like this:

// create XML element representing one "Item", containing a "Name" and an "Amount" 
// and add it to the given parent element
private void AddItem(XElement parent, string itemName, int amount)
{
    // create new XML element for item
    XElement newItem = new XElement("Item");
    // add the name
    newItem.Add(XElement.Parse("<Name>" + itemName + "</Name>"));
    // add the amount
    newItem.Add(XElement.Parse("<Amount>" + amount + "</Amount>"));
    // add to parent XML element given by caller
    parent.Add(newItem);
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    // create new document (in your case you would do this only once, 
    // not on every button click)
    XDocument doc = XDocument.Parse("<Items />");

    // doc.Root is <Items /> - lets add some items
    AddItem(doc.Root, "My item", 42);
    AddItem(doc.Root, "Another item", 84);

    // check if we succeeded (of course we did!)
    Debug.WriteLine(doc.ToString());
}

AddItem can be called multiple times and every call adds one item to your <Items> element. You would call it every time the user clicks the button.

The structure of your XML then looks like this:

<Items>
  <Item>
    <Name>My item</Name>
    <Amount>42</Amount>
  </Item>
  <Item>
    <Name>Another item</Name>
    <Amount>84</Amount>
  </Item>
</Items>

Edit:

And for saving and loading XML to/from isolated storage:

using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("myfile.xml", System.IO.FileMode.Create, isf))
    {
        doc.Save(stream);
    }
}


using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("myfile.xml", System.IO.FileMode.Open, isf))
    {
        doc = XDocument.Load(stream);
    }
}

i think this is a better and the right way to write XML file. you can use this snippet in a loop to write the whole xml you want

IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream
XmlWriterSettings settings = new XmlWriterSettings();        
settings.Indent = true;   
XmlWriter writer = new XmlWriter(isoStream, settings);



        writer.Formatting = Formatting.Indented;
        writer.Indentation = 3;
        writer.WriteStartDocument();
        writer.WriteStartElement("elementName");

        writer.WriteAttributeString("attName", "value");
        writer.WriteValue("value of elem");
        writer.WriteEndElement();
        writer.WriteEndDocument();
        writer.Close();            

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM