Переписываю в xml - PullRequest
       16

Переписываю в xml

0 голосов
/ 07 октября 2011

У меня есть список и текстовое поле в моем WPF.Я сохраняю эти значения в xml, например:

private void textBox1_LostFocus(object sender, RoutedEventArgs e)
{
    if (listBox1.SelectedValue != null)
    {
        writer.WriteStartElement("Attribute",textBox1.Text);
        ListBoxItem a = listBox1.SelectedValue as ListBoxItem;
        if (a != null)
        {
            writer.WriteAttributeString("Name", a.Content.ToString());
        }
        //writer.WriteAttributeString("Value", textBox1.Text);
        writer.WriteEndElement();
        writer.Flush();
    }
}

Но когда я выбираю элемент, который уже выбран и сохранен, я хочу, чтобы мой xml был переписан.Теперь я получаю что-то вроде этого:

<?xml version="1.0" encoding="utf-8"?>
<Query_advanced>
  <Query>
    <Attribute Name="Patient Name" xmlns="John" />
    <Attribute Name="Patient Age" xmlns="23" />
    <Attribute Name="Patient ID" xmlns="12" />
    <Attribute Name="Patient Name" xmlns="Mary" />
  </Query>
</Query_advanced>

Как мне это сделать?Спасибо!

Ответы [ 3 ]

1 голос
/ 07 октября 2011

Почему бы просто не использовать класс XmlSerializer ?

Вы можете просто создать объект Patient. Затем сериализуйте и десериализуйте из него как:

[Serializable]
public class Patient
{
    public string Name {get; set;}
    public int Age {get; set;}
    public int Id {get; set;}

    public override string ToString()
    {
         return Name;
    }
}
...
public void Serialize(List<Patient> pList)
{
    using (Stream writer = new FileStream(filename, FileMode.Create))
    {
        var serializer = new XmlSerializer(typeof (List<Patient>));
        serializer.Serialize(writer, pList);
    }
}

public List<Patient> Deserialize()
{
    using (Stream reader = new FileStream(filename, FileMode.Open))
    {
        var serializer = new XmlSerializer(typeof (List<Patient>));

        var pList = (List<Patient>) serializer.Deserialize(reader);

        return pList;
    }
}

Теперь вы можете создать обычный объект пациента, сохранить его с помощью сериализации и загрузить обратно в объект с помощью десериализации.

Возможно, вы захотите использовать его так:

public List<Patient> Patients; // Patient collection
//Populate your listBox with these patient objects.

private void textBox1_LostFocus(object sender, RoutedEventArgs e)
{
     if (listBox1.SelectedItem == null) return;

     var patient = listBox1.SelectedItem as Patient; // Get the selected PObj;

     patient.Name = textBox1.Text; 

     Serialize(Patients); //Save the list to xml
}
0 голосов
/ 11 октября 2011

Принимая во внимание ответ @ bitbonk и меняя его, это сработало для меня:

private void textBox1_LostFocus(object sender, RoutedEventArgs e){
    if (listBox2.SelectedValue != null){
         string name = listBox2.SelectedItem.ToString();
         string value = textBox1.Text;
         if(!attributes_dict.ContainsKey(name)){
             //attributes.Add(name, value);
             attributes_dict[name] = value;
             //UpdateXml();
         }else{
             attributes_dict.Remove(name);
             attributes_dict.Add(name, value);
             //UpdateXml();
         }
     }
}


private  void button1_Click(object sender, RoutedEventArgs e){
     foreach (KeyValuePair<string, string> attribute in this.attributes_dict){
          writer.WriteStartElement("Attribute", textBox1.Text);
          if(attribute.Key != null){
               writer.WriteAttributeString("Name1", attribute.Key);
          }
          writer.WriteAttributeString("Value1", attribute.Value);                                     
          writer.WriteEndElement();
     }
     writer.Flush();
     writer.WriteEndElement();
     writer.Flush();
     writer.WriteEndDocument();
     writer.Close();
}
0 голосов
/ 07 октября 2011
private Dictionary<string, string> attributes = new Dictionary<string, string>();    

private void textBox1_LostFocus(object sender, RoutedEventArgs e)
{
    if (listBox1.SelectedValue != null) 
    {
        ListBoxItem a = listBox1.SelectedValue as ListBoxItem;
        string name = a.Content.ToString();
        string value = textBox1.Text;
        if (!this.attributes.ContainsKey(name) || this.attributes[name] != value)
        {
             this.attributes[name] = value;
             this.UpdateXml();
        }            
    }
}

private void UpdateXml()
{
    foreach(KeyValuePair<string,string> attribute in this.attributes)
    {
        writer.WriteStartElement("Attribute",textBox1.Text);
        if (attribute.Key != null)
        {
            writer.WriteAttributeString("Name", attribute.Key);
        }

        writer.WriteAttributeString("Value", attribute.Value);
        writer.WriteEndElement();
    }

    writer.Flush();
}
...