Serializacja xml

0

witam,

Używam MVS 2010, mam w c#: button'ik - "Save" i ListBox'a. Mam problem bo chciałbym aby w xml'u zapisywał się w ten sposób, że w listBoxa wstawiam:
Jan
Kowalski

a w xml'u aby Jan był w znaczniku 'imie', a kowalski 'nazwisko'. Nie bardzo wiem jak to uzyskać bo jeżeli tutaj:

foreach (String item in listBox1.Items)
            {
                xwriter.WriteStartElement("Imie");
                xwriter.WriteString(item);
                xwriter.WriteEndElement();
            }

dodałbym nazwisko np.:

foreach (String item in listBox1.Items)
            {
                xwriter.WriteStartElement("Imie");
                xwriter.WriteString(item);
                xwriter.WriteEndElement();

                xwriter.WriteStartElement("Nazwisko");
                xwriter.WriteString(item);
                xwriter.WriteEndElement();
            }

to oczywiście zarówno Jan jak i kowalski będą w każdym ze znaczników.

<Imie>Jan</Imie>
<Nazwisko>Jan</Nazwisko>
<Imie>Kowalski</Imie>
<Nazwisko>Kowalski</Nazwisko>

Czy jest jakiś w miarę łatwy sposób aby jan był w imieniu a kowalski w nazwisku ?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace SaveListBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            XmlTextWriter xwriter = new XmlTextWriter("savefile.xml", Encoding.Unicode);
            xwriter.WriteStartDocument();
            xwriter.WriteStartElement("XMLFILE");

            foreach (String item in listBox1.Items)
            {
                xwriter.WriteStartElement("Imie");
                xwriter.WriteString(item);
                xwriter.WriteEndElement();
            }

            xwriter.WriteEndElement();
            xwriter.WriteEndDocument();
            xwriter.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

       }
    }
}
0

W ListBox-ie item-y przechowywane są jako elementy klasy object. Można tu wrzucić element dowolnej klasy, ponieważ każdy obiekt w .NET posiada metodę ToString().

Stwórz sobie klasę, która będzie przechowywała wartość typu string i właściwość bool, która będzie zwracała odpowiednią flagę w przypadku gdy wartość typu string będzie nazwiskiem i odwrotną flagę gdy wartość ta będzie imieniem. Dodatkowo obowiązkowo należy przeciążyć metodę ToString() tak aby zwracała stringa z obiektu Twojej klasy

0

Jakoś absurdalnie to masz, imiona i nazwiska po kolei? Jak będziesz miał ich w Listboxie 20 to jak ogarniesz które to imię a które nazwisko?

Ja to bym raczej zrobił 2 texxboxy na imię i nazwisko. Po wciśnięciu przycisku dodawałbyś osobę do listy osób i wpis do listboxa, coś ala Imię Nazwisko.
A jakoś tak serializował listę: http://forum.codecall.net/topic/49246-c-serializationdeserialization-of-listt/

0

tak, obaj macie racje. Ja w c# jestem zielony, nie chodzi tylko o dwa znaczniki. Ma być klasa ksiegarnia i atrybuty autor, tytuł, rok wydania, opis, cena itp. No i mam tutoriale/gotowe kody mnóstwo materiałów na internecie ale no nie potrafię no dlaczego tak prosta klasa mi nie działa, co robię źle (namespace cannot directly contain members such as fields or methods):

using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication1
{
    public class Books
    {
        public string Author { get; set; }
        public string Title { get; set; }
        public string Genre { get; set; }
        public int Price { get; set; }
        public string Publish_date { get; set; }
        public string Description { get; set; }

        public Books()
        {
        }

        public Books(string sAuthor, string sTitle, string sGenre, int nPrice, string sPublish_date, string sDescription)
        {
            Author = nAuthor;
            Title = sTitle;
            Genre = sGenre;
            Price = nPrice;
            Publish_date = sPublish_date;
            Description = sDescription;
        }
    }
    List<Books> oBookList = new List<Books>();
    oBookList.Add(new Books("Gambardella, Matthew", "XML Developer's Guide", "Computer", 44.95, "2000-10-01", "An in-depth look at creating applications with XML."));
    oBookList.Add(new Books("Ralls, Kim", "Midnight Rain", "Fantasy",5.95, "2000-12-16", "A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world."));
    oBookList.Add(new Books("Corets, Eva", "Maeve Ascendant", "Fantasy",5.95, "2000-11-17", "After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society."));
    oBookList.Add(new Books("Corets, Eva", "Oberon's Legacy", "Fantasy", 5.95, "2001-03-10", "In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for the inhabitants of London. Sequel to Maeve Ascendant."));
    oBookList.Add(new Books("Corets, Eva", "The Sundered Grail", "Fantasy", 5.95, "2001-09-10", "The two daughters of Maeve, half-sisters, battle one another for control of England. Sequel to Oberon's Legacy."));
    oBookList.Add(new Books("Randall, Cynthia", "Lover Birds", "Romance", 4.95, "2000-09-02", "When Carla meets Paul at an ornithology conference, tempers fly as feathers get ruffled."));
    oBookList.Add(new Books("Thurman, Paula", "Splish Splash", "Romance", 4.95, "2000-11-02", "A deep sea diver finds true love twenty thousand leagues beneath the sea."));
    oBookList.Add(new Books("Knorr, Stefan", "Creepy Crawlies", "Horror", 4.95, "2000-12-06", "An anthology of horror stories about roaches,centipedes, scorpions  and other insects."));
    oBookList.Add(new Books("Kress, Peter", "Paradox Lost", "Science Fiction",6.95, "2000-11-02", "After an inadvertant trip through a Heisenberg Uncertainty Device, James Salway discovers the problems of being quantum."));
    oBookList.Add(new Books("O'Brien, Tim", "Microsoft .NET: The Programming Bible", "Computer", 36.95, "2000-12-09", "Microsoft's .NET initiative is explored in detail in this deep programmer's reference."));
    oBookList.Add(new Books("O'Brien, Tim", "MSXML3: A Comprehensive Guide", "Computer", 36.95, "2000-12-01", "The Microsoft MSXML3 parser is covered in detail, with attention to XML DOM interfaces, XSLT processing, SAX and more."));
    oBookList.Add(new Books("Galos, Mike", "Visual Studio 7: A Comprehensive Guide", "Computer", 49.95, "2001-04-16", "Microsoft Visual Studio 7 is explored in depth, looking at how Visual Basic, Visual C++, C#, and ASP+ are integrated into a comprehensive development environment."));
    XmlRootAttribute oRootAttr = new XmlRootAttribute();
    oRootAttr.ElementName = "Book";
    oRootAttr.IsNullable = true;
    XmlSerializer oSerializer = new XmlSerializer(typeof(List<Books>), oRootAttr);
    StreamWriter oStreamWriter = null;
    try
    {
        oStreamWriter = new StreamWriter("books2.xml");
        oSerializer.Serialize(oStreamWriter, oBookList);
    }
    catch (Exception oException)
    {
        Console.WriteLine("Aplikacja wygenerowała następujący wyjątek: " + oException.Message);
    }
    finally
    {
        if (null != oStreamWriter)
        {
            oStreamWriter.Dispose();
        }
    }
}
0

Po pierwsze, kod od: List<Books> oBookList = new List<Books>(); do końca powinien być w metodzie jakiejś klasy, a nie bezpośrednio w namespace (o tym właśnie mówi błąd).
Po drugie, w konstruktorze przyjmujesz int nPrice, natomiast wywołujesz przekazując liczby zmiennoprzecinkowe.
Po trzecie, skoro klasa przechowuje dane o JEDNEJ książce, to powinna nazywać się Book, a nie Books.
Po czwarte, wywal tę okropną notację węgierską z konstruktora.
Po piąte, cywilizowana serializacja wygląda tak:

using (FileStream fs = new FileStream(@"D:\TempDev\books.xml", FileMode.Create))
{
    new XmlSerializer(typeof(List<Book>)).Serialize(fs, lista);
} 
0

To co kolega próbował zrobić to nie jest serializacja tylko tworzenie dokumentu xml od zera. Coś w rodzaju wymyślania koła na nowo.

0
List<Books> oBookList = new List<Books>();
    oBookList.Add(new Books("Gambardella, Matthew", "XML Developer's Guide", "Computer", 44.95, "2000-10-01", "An in-depth look at creating applications with XML."));
    oBookList.Add(new Books("Ralls, Kim", "Midnight Rain", "Fantasy",5.95, "2000-12-16", "A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world."));

o dzizas..

var oBookList = new List<Books> {
    new Books("Gambardella, Matthew", "XML Developer's Guide", "Computer", 44.95, "2000-10-01",
              "An in-depth look at creating applications with XML."),
    new Books("Ralls, Kim", "Midnight Rain", "Fantasy",5.95, "2000-12-16",
              "A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.")
};

i nie Books tylko Book, jeśli to jedna książka. Listę możesz nazwać "books".

1 użytkowników online, w tym zalogowanych: 0, gości: 1