如何使用 DataContractSerializer 从 XMLDocument 的单个节点进行反序列化?
DataContractSerializer 在 ReadObject 中使用的读取器似乎是基于流的。我已经有一个 XMLDocument,并且我想反序列化该文档的一部分。
在此代码片段中,我从文件流反序列化 MyItem 对象:
Dim fs As New FileStream("c:\myinputfile.xml", FileMode.Open)
Dim reader As XmlDictionaryReader = XmlDictionaryReader.CreateTextReader(fs, New XmlDictionaryReaderQuotas())
Dim ser As New DataContractSerializer(GetType(MyItemClass))
Dim deserializedMyItem As ClassTemplate = CType(ser.ReadObject(reader, True), MyItemClass)
但是如果我只想反序列化文档的一部分,该怎么办?
Dim MyItemNode as Xml.XmlNode = parentDoc.selectSingleNode("MyItemElementName")
Dim deserializedMyItem As MyItemClass = getMyItemFromNode(MyItemNode)
getMyItemFromNode 是什么样子的?
The readers that DataContractSerializer uses in ReadObject seem to be stream-based. I already have an XMLDocument, and I would like to deserialize one part of that document.
In this code snippet, I am deserializing a MyItem object from a filestream:
Dim fs As New FileStream("c:\myinputfile.xml", FileMode.Open)
Dim reader As XmlDictionaryReader = XmlDictionaryReader.CreateTextReader(fs, New XmlDictionaryReaderQuotas())
Dim ser As New DataContractSerializer(GetType(MyItemClass))
Dim deserializedMyItem As ClassTemplate = CType(ser.ReadObject(reader, True), MyItemClass)
but what if instead I want to deserialize just a part of a document.
Dim MyItemNode as Xml.XmlNode = parentDoc.selectSingleNode("MyItemElementName")
Dim deserializedMyItem As MyItemClass = getMyItemFromNode(MyItemNode)
What does getMyItemFromNode look like?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除非有更好的方法来流式传输它,否则这是使用内存流的解决方案:
将其推送到流的代码来自 此回复相关问题。
Unless there is a better way that streaming it, here's a solution using the memorystream:
Code for pushing it to a stream came from this response to a related question.
使用 [
CreateDictionaryReader](http://msdn.microsoft.com/en-us/library/system.xml.xmldictionaryreader.createdictionaryreader.aspx) 以及指向所需节点的
XmlReader`:Use [
CreateDictionaryReader](http://msdn.microsoft.com/en-us/library/system.xml.xmldictionaryreader.createdictionaryreader.aspx) with an
XmlReader` pointing to the node you want: