I have a listbox and a textbox in my WPF. Im saving these values into an xml like this:
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();
}
}
But when I select an item that is already selected and saved, i want my xml to be re-written. Now i get something like this:
<?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>
How can I go about this? Thanks!
Taking @bitbonk's answer answer into account and modifying, this worked for me:
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();
}