我使用以下代码将许多类序列化为XML文件
static void GetFromDBToXml()
{
var thejob = Xmltodb.Singleton.DBManager.GetSingleObject<job>("jobid", JobData.Job.Jobid);
var theparts = Xmltodb.Singleton.DBManager.GetListOfObjects<parts>("jobid", JobData.Job.Jobid);
var thesurv = Xmltodb.Singleton.DBManager.GetListOfObjects<jobsurvey>("jobid", JobData.Job.Jobid);
try
{
using (var fs = new FileStream(Path.Combine(Xmltodb.Singleton.ContentDirectory, "temp.xml"), FileMode.OpenOrCreate))
{
var xmlSerializer = new XmlSerializer(typeof(job));
xmlSerializer.Serialize(fs, thejob);
xmlSerializer = new XmlSerializer(typeof(parts));
foreach (var p in theparts)
xmlSerializer.Serialize(fs, p);
xmlSerializer = new XmlSerializer(typeof(jobsurvey));
foreach (var s in thesurv)
xmlSerializer.Serialize(fs, s);
}
}
catch (InvalidOperationException ex)
{
Console.WriteLine("Can't write the xml file : {0}--{1}", ex.Message, ex.StackTrace);
}
}
代码直接从SQLite中提取并写入XML文件。
虽然这有效,但在每个类的结尾和下一个的开始时,我每次都会添加XML标头。换句话说
</jobsurvey>
<?xml version="1.0" encoding="utf-8">
<parts xmlns:xsi="http://www.w3.org ...
有没有办法阻止序列化程序为每个被序列化的类生成<?xml
和xmlns:
部分而不必创建文件,然后重新分析以删除我不需要的这些位?
答案 0 :(得分:0)
你可以尝试这样的事情。 这里重要的是XMLWriterSettings和XmlSerializerNamespaces。
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
MemoryStream ms = new MemoryStream();
XmlWriter writer = XmlWriter.Create(ms, settings);
XmlSerializerNamespaces names = new XmlSerializerNamespaces();
names.Add("", "");
XmlSerializer cs = new XmlSerializer(typeof(Cat));
cs.Serialize(writer, new Cat { Lives = 9 }, names);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms);
var xml = sr.ReadToEnd();