【发布时间】:2014-03-09 08:30:44
【问题描述】:
在我使用按钮创建的一个类中单击 XML 文档:
private void buttonCreate_Click(object sender, RoutedEventArgs e)
{
DialogResult result = folderElg.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
textBoxPath.Text = folderElg.SelectedPath;
userConfigurePath = folderElg.SelectedPath;
}
XmlDocument toolConfig = new XmlDocument();
XmlNode myRoot;
myRoot = toolConfig.CreateElement("Tool");
toolConfig.AppendChild(myRoot);
toolConfig.Save(@userConfigurePath + "\\config.xml");}
我没有问题。文件夹已创建,xml 文件也已创建。
所以在另一个类中,我想将对象序列化到 xml 文件“config.xml”中(变量 userConfigurePath 在上面提到的类中是静态的):
public partial class MainWindow : Window
{
private string inputNewTool = "";
private OpenFileDialog dlg = new OpenFileDialog();
public MainWindow()
{
InitializeComponent();
}
private void buttonAdd_Click(object sender, RoutedEventArgs e)
{
InputDialog input = new InputDialog();
input.ShowDialog();
inputNewTool = input.enteredTxt;
if (inputNewTool != null)
{
System.Windows.Forms.MessageBox.Show("Chose the Tool's directory");
dlg.DefaultExt = ".txt";
dlg.Filter = "Text documents (.txt)|*.txt";
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Tool tool = new Tool();
tool.Name = inputNewTool;
tool.Path = dlg.FileName;
XmlSerializer serializer = new XmlSerializer(tool.GetType());
StreamWriter writer = new StreamWriter(@Start.userConfigurePath +
"\\config.xml");
serializer.Serialize(writer.BaseStream, tool);
}
}
结果是对象未保存在 config.xml 文件中。为什么?
编辑工具类:
public class Tool
{
public string Name { get; set; }
public string Path { get; set; }
public Tool() { }
}
第二次编辑:
我发现在创建 xml 文件时,我无法删除这些文件夹(在应用程序关闭后)。为什么?
第三次编辑:
我改变了我的代码:
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Tool tool = new Tool();
tool.Name = inputNewTool;
tool.Path = dlg.FileName;
XmlSerializer serializer = new XmlSerializer(tool.GetType());
using (var writer = new StreamWriter(@Start.userConfigurePath +
"\\config.xml"))
{
serializer.Serialize(writer.BaseStream, tool);
writer.Close();
}
现在第一个对象被序列化了。但是,如果我以相同的方式创建另一个工具,config.xml 就不会使用它。只有第一个工具被序列化了:
<?xml version="1.0"?>
<Tool xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>dffss</Name>
<Path>D:\Users\xxxx\Documents\schulewochenbericht.txt</Path>
</Tool>
【问题讨论】:
-
object isn't saved in the config.xml是什么意思?你有错误吗?或者你得到一个意外的输出? -
如果我打开 xml 文件没有带有他的名字和路径的对象
-
您的 Tool 类是否标有可序列化属性?
-
公共字符串名称 { 获取;放; } 公共字符串路径 { 获取;设置;
-
@rageit
serializable是 BinaryFormatter 需要的,使用 XmlSerializer 时不需要
标签: c# xml streamwriter