简体   繁体   English

反序列化XML文件的最有效方法是什么

[英]What is the most efficient way to Deserialze an XML file

Aloha, 阿罗哈,

I have a 8MB XML file that I wish to deserialize. 我有一个8MB XML文件,我希望反序列化。 I'm using this code: 我正在使用此代码:

public static T Deserialize<T>(string xml)
{
    TextReader reader = new StringReader(xml);
    Type type = typeof(T);
    XmlSerializer serializer = new XmlSerializer(type);
    T obj = (T)serializer.Deserialize(reader);
    return obj; 
}

This code runs in about a minute, which seems rather slow to me. 这段代码运行大约一分钟,这对我来说似乎相当慢。 I've tried to use sgen.exe to precompile the serialization dll, but this didn't change the performance. 我曾尝试使用sgen.exe预编译序列化dll,但这并没有改变性能。

What other options do I have to improve performance? 我还有哪些其他选择来提高性能?

[edit] I need the object that is created by the deserialization to perform (basic) transformations on. [编辑]我需要反序列化创建的对象来执行(基本)转换。 The XML is received from an external webservice. XML是从外部Web服务接收的。

The XmlSerializer uses reflection and is therefore not the best choice if performance is an issue. XmlSerializer使用反射,因此如果性能问题,则不是最佳选择。

You could build up a DOM of your XML document using the XmlDocument or XDocument classes and work with that, or, even faster use an XmlReader . 您可以使用XmlDocumentXDocument类构建XML文档的DOM并使用它,或者甚至更快地使用XmlReader The XmlReader however requires you to write any object mapping - if needed - yourself. 但是, XmlReader要求您自己编写任何对象映射(如果需要)。

What approach is the best depends stronly on what you want to do with the XML data. 最好的方法取决于您想要对XML数据做什么。 Do you simply need to extract certain values or do you have to work and edit the whole document object model? 您只需要提取某些值,还是必须工作和编辑整个文档对象模型?

Yes it does use reflection, but performance is a gray area. 是的它确实使用了反射,但性能是一个灰色区域。 When talking an 8mb file... yes it will be much slower. 在谈论8mb文件时......是的,它会慢得多。 But if dealing with a small file it will not be. 但如果处理一个小文件,它将不会。

I would NOT saying reading the file vial XmlReader or XPath would be easier or really any faster. 我不会说读取文件样式瓶XmlReader或XPath会更容易或更快。 What is easier then telling something to turn your xml to an object or your object to XML...? 然后告诉某些东西将你的xml变成一个对象或你的对象变成XML会更容易吗? not much. 不多。

Now if you need fine grain control then maybe you need to do it by hand. 现在,如果你需要细粒度控制,那么你可能需要手工完成。

Personally the choice is like this. 个人选择是这样的。 I am willing to give up a bit of speed to save a TON of ugly nasty code. 我愿意放弃一点速度来保存一堆令人讨厌的令人讨厌的代码。

Like everything else in software development there are trade offs. 像软件开发中的其他所有东西一样,存在权衡取舍。

您可以尝试在“T”类中编写IXmlSerializable来编写自定义逻辑来处理XML。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM