C# 重写为xml

C# 重写为xml,c#,wpf,xml,listbox,xmlwriter,C#,Wpf,Xml,Listbox,Xmlwriter,我的WPF中有一个列表框和一个文本框。我正在将这些值保存到xml中,如下所示: private void textBox1_LostFocus(object sender, RoutedEventArgs e) { if (listBox1.SelectedValue != null) { writer.WriteStartElement("Attribute",textBox1.Text); ListBoxItem a = listBox1.Se

我的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>
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
}

我该怎么办?谢谢

private Dictionary attributes=new Dictionary();
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();
}
private void textBox1_LostFocus(对象发送方,RoutedEventArgs e) { 如果(listBox1.SelectedValue!=null) { ListBoxItem a=listBox1.SelectedValue作为ListBoxItem; 字符串名称=a.Content.ToString(); 字符串值=textBox1.Text; if(!this.attributes.ContainsKey(name)| | this.attributes[name]!=value) { this.attributes[name]=值; this.UpdateXml(); } } } 私有void UpdateXml() { foreach(此.attributes中的KeyValuePair属性) { writer.writeStarteElement(“属性”,textBox1.Text); 如果(attribute.Key!=null) { WriteAttributeString(“Name”,attribute.Key); } WriteAttributeString(“Value”,attribute.Value); writer.writeedelement(); } writer.Flush(); }
为什么不直接使用该类

您可以创建一个患者对象。然后从中序列化和反序列化,如:

[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;
    }
}
[可序列化]
公立病人
{
公共字符串名称{get;set;}
公共整数{get;set;}
公共int Id{get;set;}
公共重写字符串ToString()
{
返回名称;
}
}
...
公共void序列化(列表pList)
{
使用(streamwriter=newfilestream(文件名,FileMode.Create))
{
var serializer=newxmlserializer(typeof(List));
serializer.Serialize(writer,pList);
}
}
公共列表反序列化()
{
使用(流读取器=新文件流(文件名,FileMode.Open))
{
var serializer=newxmlserializer(typeof(List));
var pList=(列表)序列化程序。反序列化(读取器);
返回层;
}
}
现在,您可以像普通一样创建一个patient对象,使用serialize保存它,并使用deserialize将其加载回一个对象

您可能希望这样使用它:

<?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>
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
}
公开患者名单;//病人收集
//用这些患者对象填充列表框。
private void textBox1_LostFocus(对象发送方,RoutedEventArgs e)
{
if(listBox1.SelectedItem==null)返回;
var patient=listBox1.SelectedItem as patient;//获取所选PObj;
patient.Name=textBox1.Text;
序列化(患者);//将列表保存为xml
}
考虑到答案并进行修改,这对我来说很有效:

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();
}
private void textBox1\u LostFocus(对象发送方,RoutedEventArgs e){
如果(listBox2.SelectedValue!=null){
string name=listBox2.SelectedItem.ToString();
字符串值=textBox1.Text;
如果(!attributes_dict.ContainsKey(name)){
//属性。添加(名称、值);
属性\u dict[名称]=值;
//UpdateXml();
}否则{
属性(名称);
添加属性(名称、值);
//UpdateXml();
}
}
}
私有无效按钮1\u单击(对象发送者,路由目标){
foreach(此.attributes\u dict中的KeyValuePair属性){
writer.writeStarteElement(“属性”,textBox1.Text);
如果(attribute.Key!=null){
WriteAttributeString(“Name1”,attribute.Key);
}
WriteAttributeString(“Value1”,attribute.Value);
writer.writeedelement();
}
writer.Flush();
writer.writeedelement();
writer.Flush();
writer.WriteEndDocument();
writer.Close();
}

hi,@bitbonk:我没有得到正确的结果。他们似乎来了更多次,而不是被取代(谢谢!您需要删除旧的XML。@user877852您尝试过XmlSerializer类吗?我个人更喜欢它而不是XmlWriter。我相信更多人会同意。IMO.HI@bitbonk您的意思是在代码中使用更干净的方法吗?请您指导我如何操作。我是新的,我真的不知道如何操作!:(但我确实想知道我现在如何阅读此xml..我想xmlns会引起一些问题:(如果您不介意向我展示整个form1.cs,我不介意让它与XmlSerializer一起工作,如我的回答所示。