我从一个Web服务下面的XML,我想转换为.NET对象:反序列化与F#
let xmlString = "<?xml version=\"1.0\"?>
<logInResponse>
<result>OK</result>
<xmlLogIn>
<session>11C0ED6F8F7288855FC73C99979A9732.TOGKE6VP9aE8abcdLXaVXg</session>
<user>WallStreetScumbag1</user>
<authorizations>
<insiderTrading>true</insiderTrading>
</authorizations>
</xmlLogIn>
</logInResponse>"
这是我到目前为止有:
type Result(value:XmlNode) =
member this.Value = value.InnerText
let (|Node|Result|) (node : #System.Xml.XmlNode) =
if node.Name = "result" then
Result (new Result(node))
else
Node (seq {for x in node.ChildNodes -> x})
let extract node =
let rec extract node =
match node with
| Result(p) ->
Seq.singleton p
| Node(nodes) ->
Seq.collect (fun (n) -> extract n) nodes
extract node
let xmlDoc = new XmlDocument()
xmlDoc.LoadXml(xmlString)
//type LogIn() =
//This is where I would create a .net object that mirrors the xml.
正如你可以看到一些元素在不同的元素中重复,有时元素不包括所有可以显示的元素,正如你可以在我的示例xml中看到的。这种相同的Web服务也将在其他类型的响应中重用许多这些相同的元素。是否有可能使用主动模式来创建反序列化xml我返回到对象的一般方法?看起来,这个Web服务从来没有使用属性来发送信息,它似乎都是元素内的元素,这可能会使这个问题更容易。如果我以这种错误的方式进行讨论,请随时提出更好的建议。
由于提前,
鲍勃
谢谢,这解决了我的问题的一部分,但另一部分是从这个.net对象的最佳方式。将此xml转换为LogInResponse类型的最佳方法是什么?我不确定以某种方式处理元素中元素的最佳方式,以便在其他响应包含某些相同元素时重用代码。我从我的xml字符串中删除了accounts元素来简化事情。 – Beaker 2011-04-01 02:16:52
我终于放弃了试图从我的xml中获取域对象。因为你至少回答了我的问题的一部分,所以我将其标记为答案。 – Beaker 2011-04-03 01:58:08
顺便说一句,我使用Linq to Xml来获取域对象,如果有人对我如何解决我的问题感到好奇。 – Beaker 2011-04-03 01:58:49