Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Разработка Windows Forms > Редактирование слов в xml файле с помощю формы


Автор: Butadion 17.4.2011, 10:53
Здраствуйте.Помогите или подскажите как сделать редактировае слов в xml файде.Зарание спасибо.
Код

 public partial class Form1 : Form
    {

        const string FILE = "Dictionary.xml";

        MyDictionary dictionary;
        public Form1()
        {
            InitializeComponent();
            dictionary = new MyDictionary(FILE);

            comboBox1.SelectedIndex = 0;
        }

        XDocument dict;
        string fileName = "Dictionary.xml";
        public enum Direction
        {
            Rus2Ukr,
            Ukr2Rus,
        };

        public struct Word
        {
            public string Rus;
            public string Ukr;

            public Word(string rus, string ukr)
            {
                this.Rus = rus;
                this.Ukr = ukr;
            }
        };

        public class MyDictionary
        {
            private List<Word> dictionary;

            public MyDictionary(string fileName)
            {
                dictionary = new List<Word>();
                LoadDictionary(fileName);
            }

            public string ukrTranslate(Direction direction, string input)
            {
                foreach (Word word in dictionary)
                {
                    if (input.Equals(word.Rus, StringComparison.CurrentCultureIgnoreCase))
                        return word.Ukr;
                }
                throw new Exception("Слово не найденно");
                //return input;
            }

            public string ruTranslate(Direction direction, string input)
            {
                foreach (Word word in dictionary)
                {
                    if (input.Equals(word.Ukr, StringComparison.CurrentCultureIgnoreCase))
                        return word.Rus;
                }
                throw new Exception("Слово не найденно");
                //return input;
            }



            private void LoadDictionary(string fileName)
            {
                if (!File.Exists(fileName))
                {
                    MessageBox.Show("File \"" + fileName + "\", not found!");
                    return;
                }

                XmlDocument doc = new XmlDocument();
                doc.Load(fileName);
                foreach (XmlElement el in doc.GetElementsByTagName("Dictionary")[0])
                    dictionary.Add(new Word(el["Rus"].InnerText, el["Ukr"].InnerText));
            }
        }
 private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                translate();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // загрузили документ в память 
            if (!File.Exists(fileName))
                dict = XDocument.Parse("<Dict></Dict>");
            else
                dict = XDocument.Load(fileName);

        }
 private void button2_Click(object sender, EventArgs e) //выводит на 2 форму данные xml 
        {
            XmlDocument doc = new XmlDocument();
            // Загружаем 
            var sb = new StringBuilder();
            string FileName = "Dictionary.xml";
            doc.Load(FileName);
            // xmlDoc.LoadXML(s1); 
            // Получаем чилды корневого элемента 
            foreach (XmlNode table in doc.DocumentElement.ChildNodes)
            {
                // перебираем все атрибуты элемента 
                foreach (XmlAttribute attr in table.Attributes)
                {

                    string s = attr.Name + " : " + attr.Value;
                }
                // перебираем всех чилдов текущего узла parentNode.AppendChild(node);
                foreach (XmlNode ch in table.ChildNodes)
                {
                    //... 
                }
                // Получаем текст в текущем узле 
                sb.AppendLine(table.InnerText);
            }

            Form2 fm2 = new Form2(sb.ToString());
            fm2.Show();

        }
public partial class Form2 : Form
    {
        string Txt=string.Empty;
        public Form2(string txt)
        {
            InitializeComponent();
            Txt= txt;
        }
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            richTextBox1.Text = Txt;    // показываает содержимое xml
        }

        
        private void button1_Click(object sender, EventArgs e)
        {
            richTextBox1.ReadOnly = false;
        }

        private void button2_Click(object sender, EventArgs e)
        {
          // нужно реализовать редактирование =(
        }
    }
}

Автор: Voyager 17.4.2011, 20:16
Для начала русский язык выучи.
Потом пиши что конкретно не получается.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)