开发者

How do I deserialize a namespaced element to an object in .net?

Given this XML snippet:

...
<InSide:setHierarchyUpdates>
   <automaticUpdateInterval>5</automaticUpdateInterval>
   <shouldRunAutomaticUpdates>true<shouldRunAutomaticUpdates>
</InSide:setHierarchyUpdates>
...

I am attempting to serialize this object:

Imports System.Xml.Serialization
<XmlRoot(ElementName:="setHierarchyUpdates", namespace:="InSide")> _
Public Class HierarchyUpdate
    <XmlElement(ElementName:="shouldRunAutomaticUpdates")> _
    Public shouldRunAutomaticUpdates As Boolean
    <XmlElement(ElementName:="automaticUpdateInterval")> _
      开发者_如何转开发Public automaticUpdateInterval As Integer
End Class

Like this:

Dim hierarchyUpdater As New HierarchyUpdate
Dim x As New XmlSerializer(hierarchyUpdater.GetType)
Dim objReader As Xml.XmlNodeReader = New Xml.XmlNodeReader(myXMLNode)
hierarchyUpdater = x.Deserialize(objReader)

However, the object, after deserialization, has values of false and zero. If I switch the objReader to a streamreader and read this in as a file, with none of its parents and no namespaces, it works:

<setHierarchyUpdates>
   <automaticUpdateInterval>5</automaticUpdateInterval>
   <shouldRunAutomaticUpdates>true<shouldRunAutomaticUpdates>
</setHierarchyUpdates>

What am I doing wrong? Should I use something other than XMLRoot in the class definition, because, as an XML node, it's not really the root? If so, what? Why are no errors returned when this fails?


Just simply specify the default namespace to use in your call to the XmlSerializer constructor:

Dim hierarchyUpdater As New HierarchyUpdate
Dim x As New XmlSerializer(hierarchyUpdater.GetType, "http://yournamespace.org")
Dim objReader As Xml.XmlNodeReader = New Xml.XmlNodeReader(myXMLNode)
hierarchyUpdater = x.Deserialize(objReader)

Note: the InSide you're using is most probably only the XML namespace prefix - not the real XML namespace. Somewhere in your XML document, you should see a definition something like:

xmlns:InSide="http://yournamespace.org"  

(or something similar) - you need to use the actual namespace - not the prefix - in the XmlSerializer constructor call

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜