开发者

How can I use DataContractSerializer to deserialize from a single node of an XMLDocument?

The开发者_如何学JAVA 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?


Unless there is a better way that streaming it, here's a solution using the memorystream:

Function getMyItemFromNode(ByVal itemNode as Xml.XmlNode) as MyItemClass
    Dim stm As New MemoryStream()
    Dim stw  As New StreamWriter(stm)
    stw.Write(itemNode.OuterXml)
    stw.Flush()
    stm.Position = 0
    Dim reader As XmlDictionaryReader = XmlDictionaryReader.CreateTextReader(stm, New XmlDictionaryReaderQuotas())
    Dim ser As New DataContractSerializer(GetType(MyItemClass))
    Return CType(ser.ReadObject(reader, True), MyItemClass)

End Function 

Code for pushing it to a stream came from this response to a related question.


Use [CreateDictionaryReader](http://msdn.microsoft.com/en-us/library/system.xml.xmldictionaryreader.createdictionaryreader.aspx) with anXmlReader` pointing to the node you want:

Dim doc As XmlDocument = new XmlDocument()
' fill it

Dim nav as XPathNavigator = doc.CreateNavigator()
Dim docReader As XmlReader = nav.ReadSubTree()
Dim reader As XmlDictionaryReader = _
    XmlDictionaryReader.CreateDictionaryReader(docReader)
Dim ser As New DataContractSerializer(GetType(MyItemClass))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜