开发者

XML Serialization in .NET - what's wrong with this

I have xml like this:开发者_StackOverflow中文版

<?xml version="1.0" encoding="utf-8"?>
<session xmlns="http://winscp.net/schema/session/1.0" name="blah@blah.com" start="2011-10-03T15:09:30.481Z">
  <ls>
    <destination value="/incoming/monthly" />
    <files>
      <file>
        <filename value="2.txt" />
        <type value="D" />
        <modification value="2011-09-14T12:58:26.000Z" />
        <permissions value="rwxr-xr-x" />
      </file>
      <file>
        <filename value="3.txt" />
        <type value="D" />
        <modification value="2011-01-03T22:04:55.000Z" />
        <permissions value="rwxr-xr-x" />
      </file>
    </files>
    <result success="true" />
  </ls>
</session>

My representation of the following is:

  <XmlRoot("session", Namespace:="http://winscp.net/schema/session/1.0")>
    Class XMLSession
        <XmlElement("ls/files/file")>
        Public Property FileList As New List(Of XMLFile)
    End Class

 <XmlType("file")>
    Class XMLFile
        <XmlElement("filename")>
        Public Property FileName As XMLValueAttribute
        <XmlElement("type")>
        Public Property TypeName As XMLValueAttribute
        <XmlElement("permissions")>
        Public Property Permissions As XMLValueAttribute
        <XmlElement("modification")>
        Public Property ModificationDate As XMLValueAttribute
    End Class

  Class XMLValueAttribute
        <XmlAttribute("value")>
        Public Property Value As String
    End Class

Why is XMLSession.FileList.Count always 0. I hypothesize it has something to do with the declaration above it but I am not sure what is wrong with it. Maybe it can't accept a path, if not, how can I do it?


You can't describe multiple levels of XML with a single XmlElementAttribute. You need classes for each level.


If you don't want to build the classes by hand, you can get the tools to do it for you:

Assuming your XML is saved in data.xml:

xsd.exe data.xml

This will give you data.xsd which defines the XML.

xsd.exe /l:VB /n:SomeNamespace /c data.xsd

This will give you a codefile data.vb with your types defined, which you can add to your project.

Problem with this one is that there's some kind of bug, described here, which throws an error when you create a serializer around this new type. So you just need one manual tweak on the generated code, changing:

<XmlArrayItemAttribute("file", GetType(sessionLSFilesFile), IsNullable:=False)> _
'To
<XmlArrayItemAttribute("file", GetType(sessionLSFilesFile()), IsNullable:=False)> _
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜