使用XML.Serializer"pls help"在C#.net中生成XML文件. [英] XML file generation in C#.net using XML.Serializer "pls help"

查看:83
本文介绍了使用XML.Serializer"pls help"在C#.net中生成XML文件.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
在生成xml文件时,我在按钮单击事件中将一些信息存储在xml文件中,但出现错误仅一个顶级元素标签是可能的".是否可以在另一个上放置一个顶级元素标签.请帮助

单击XML代码按钮

Hello All,
I am storing some information in a xml file on a button click event,when i am generating a xml file am getting an error "Only one top level element tag is possible". Is it possible to have one top level element tag on another.Please help

XML Code on button click

FileStream fStream = new FileStream("D:\\Test.xml", FileMode.Open);
           XmlRootAttribute xroot = new XmlRootAttribute();
           xroot.ElementName = "Root";
           xroot.Namespace = "D:\\Test.xml";
           xroot.IsNullable = true;
           foreach (DictionaryEntry item in PropertyList)
           {
              XmlSerializer xml = new XmlSerializer(item.Value.GetType(),xroot);
              xml.Serialize(fStream, item.Value);
           }

推荐答案

为什么要尝试重新创建根目录?您真的不需要这样做.做这样的事情

Why are you trying to recreate the Root? you don''t really need to do that. Just do something like this

XmlSerializer xmlFormat = new XmlSerializer(item.Value.GetType());
            using (Stream fs = new FileStream(@"D:\Test.xml", FileMode.Open, FileAccess.Write, FileShare.None))
            {
                xmlFormat.Serialize(fs, item.Value);
            }



这会将序列化的对象附加到声明的文件中.如果不确定文件是否已创建,请使用



That will append the serialised object to the stated file. If you are unsure whether the file has been created yet just use

using(Stream fs = new FileStream(fileName, FileMode.OpenOrCreate,FileAccess.Write,FileShare.None))



相反,如果文件不存在,它将创建该文件.

希望对您有所帮助



instead, and that will create the file if it does not exist.

Hope this helps


没有XML或代码,我们无法指出您的错误.但是看看这个.检查您的代码和XML.
http://forums.asp.net/t/1062792.aspx/1 [ ^ ]
Without XML or code, we cannot point your mistake. But have a look at this. Check your code and XML.
http://forums.asp.net/t/1062792.aspx/1[^]


您试图为每个项目创建新的序列化器,然后使用它来使用相同的根元素将对象序列化为相同的流.看起来好像Serialize方法尝试将新序列化的数据附加到流中,为每个循环运行写入根元素.考虑移动
You''re trying to create new serializer for each item and then use it to serialize objects into the same stream using the same root element. Looks like Serialize method attempts to append newly serialized data to the stream, writing root elements for each cycle run. Consider moving
XmlSerializer xml = new XmlSerializer(item.Value.GetType(),xroot);


循环外的另一行,并将构造函数更改为另一种,从而支持类型数组(您可以使用另一个循环以静态或动态方式填充它).或将没有标题的数据写入内存流,然后将其刷新到文件:)


line outside the loop and changing constructor to another, supporting an array of types (you may fill it statically or dynamically, using another cycle). Or write data without header to the memory stream and then flush it to file :)


这篇关于使用XML.Serializer"pls help"在C#.net中生成XML文件.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆