C# XML序列化大型对象集合
序列化大型对象集合的最佳方式是什么?我正试图根据一个模式序列化和验证c#中大约70000项的大型项集合 未创建XML文件。我试过1000件物品,用较少的物品效果很好C# XML序列化大型对象集合,c#,xml,serialization,C#,Xml,Serialization,序列化大型对象集合的最佳方式是什么?我正试图根据一个模式序列化和验证c#中大约70000项的大型项集合 未创建XML文件。我试过1000件物品,用较少的物品效果很好 public void SerializeObject( Ojbect MyObj) { XmlSerializer serializer = new XmlSerializer(MyObj.GetType()); StreamWriter sw = new StreamWriter(“c:\file.xml”); s
public void SerializeObject( Ojbect MyObj)
{
XmlSerializer serializer = new XmlSerializer(MyObj.GetType());
StreamWriter sw = new StreamWriter(“c:\file.xml”);
serializer.Serialize(streamWriter, myObj);
sw.Flush();
sw.Close();
}
public void Validate()
{
XmlSchema xmlSchema = “c:\myschema.xsd”
XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
xmlReaderSettings.ValidationType = ValidationType.Schema;
xmlReaderSettings.Schemas.Add(xmlSchema);
XmlReader xmlReader = XmlReader.Create(xmlStream, xmlReaderSettings);
while (xmlReader.Read())
{
//do some stuff
}
}
我们对我们正在做的一些工作进行了一些基准测试,发现XmlSerialiser比使用XmlReader处理大型XML文件要快,但对小型XML文件则不然。我怀疑XmlValidatingReader可能会非常快。不过,您可能需要使用数据样本进行自己的基准测试 我在网上的某个地方找到了这段代码,可以根据Xml片段对xsd进行验证,只需稍作调整,这段代码可能也适用于您
public static bool Validate(string xsd, string xmlFrag)
{
if (string.IsNullOrEmpty(xmlFrag))
return false;
Trace.Indent();
XmlValidatingReader reader = null;
XmlSchemaCollection myschema = new XmlSchemaCollection();
ValidationEventHandler eventHandler = new ValidationEventHandler(ShowCompileErrors);
try
{
//Create the XmlParserContext.
XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);
//Implement the reader.
reader = new XmlValidatingReader(xmlFrag, XmlNodeType.Element, context);
//Add the schema.
myschema.Add("", xsd);
//Set the schema type and add the schema to the reader.
reader.ValidationType = ValidationType.Schema;
reader.Schemas.Add(myschema);
while (reader.Read())
{
}
Trace.WriteLine("Completed validating xmlfragment");
return true;
}
catch (XmlException XmlExp)
{
Trace.WriteLine(XmlExp.Message);
}
catch (XmlSchemaException XmlSchExp)
{
Trace.WriteLine(XmlSchExp.Message);
}
catch (Exception GenExp)
{
Trace.WriteLine(GenExp.Message);
}
finally
{
Trace.Unindent();
}
return false;
}
public static void ShowCompileErrors(object sender, ValidationEventArgs args)
{
Trace.WriteLine("Validation Error: {0}", args.Message);
}
结果如何?它快吗?慢点?好的,谢谢,这是部分原因。现在,您必须向我们展示用于序列化和验证的代码。感谢David的回答,我稍后会尝试一下,我目前将生成/编写XML文件作为我的首要任务,因为需要将这些文件取出。如果太麻烦,我可以选择不验证,尽管我认为这样做更好。从我的研究来看,XmlTextWriter似乎是更好的选择,但到目前为止,我看到的所有示例代码似乎都是手动编写每个元素和属性。这是使用这个类的唯一方法吗