重写为xml
我的 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>
我该如何解决这个问题?谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不直接使用 XmlSerializer 类?
您可以只创建一个 Patient 对象。然后对其进行序列化和反序列化,如下所示:
现在您可以像平常一样创建一个患者对象,使用序列化保存它,然后使用反序列化将其加载回对象中。
您可能想像这样使用它:
Why not just use the XmlSerializer Class?
You could just create a Patient object. Then serialize and deserialize from it like:
Now you can create a patient object like normal, save it with serialize, and load it back into an object with deserialize.
You might want to use it like this:
考虑@bitbonk的答案答案并进行修改,这对我有用:
Taking @bitbonk's answer answer into account and modifying, this worked for me: