反序列化 XML 文件最有效的方法是什么
Aloha,
我有一个 8MB 的 XML 文件,我想反序列化。 我正在使用这段代码:
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;
}
这段代码运行大约一分钟,这对我来说似乎相当慢。 我尝试使用 sgen.exe 预编译序列化 dll,但这并没有改变性能。
我还有哪些其他选择可以提高性能?
[编辑] 我需要通过反序列化创建的对象来执行(基本)转换。 XML 是从外部 Web 服务接收的。
Aloha,
I have a 8MB XML file that I wish to deserialize.
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
XmlSerializer 使用反射,因此如果性能存在问题,则不是最佳选择。
您可以使用
XmlDocument
或XDocument
类构建 XML 文档的 DOM 并使用它,或者使用XmlReader
甚至更快。 然而,XmlReader
要求您自己编写任何对象映射(如果需要)。哪种方法最好,很大程度上取决于您想要对 XML 数据执行什么操作。 您是否只需要提取某些值,或者是否必须工作和编辑整个文档对象模型?
The XmlSerializer uses reflection and is therefore not the best choice if performance is an issue.
You could build up a DOM of your XML document using the
XmlDocument
orXDocument
classes and work with that, or, even faster use anXmlReader
. TheXmlReader
however requires you to write any object mapping - if needed - yourself.What approach is the best depends stronly on what you want to do with the XML data. Do you simply need to extract certain values or do you have to work and edit the whole document object model?
是的,它确实使用了反射,但性能是一个灰色地带。 当谈论 8mb 文件时......是的,它会慢得多。 但如果处理小文件则不然。
我并不是说通过 XmlReader 或 XPath 读取文件会更容易或者更快。 还有什么比告诉某些东西将您的 xml 转换为对象或将您的对象转换为 XML 更容易的呢...? 不多。
现在,如果您需要细粒度控制,那么也许您需要手动完成。
个人的选择是这样的。 我愿意放弃一点速度来保存大量丑陋的代码。
就像软件开发中的其他事情一样,也需要权衡。
Yes it does use reflection, but performance is a gray area. When talking an 8mb file... yes it will be much slower. 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. What is easier then telling something to turn your xml to an object or your object to 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”类中实现 IXmlSerialized,编写自定义逻辑来处理 XML。
You can try implementing IXmlSerializable in your "T" class write custom logic to process the XML.