问题描述
我一直在使用第三方基于Java的web服务REST,返回将XMLNode数组。
I have been working with a 3rd party java based REST webservice, that returns an array of xmlNodes.
使用XMLNode [] respresent一个对象,我试图找出反序列化的xmlNode []对象中的最佳方式?它是先建立一个的XmlDocument和反序列化?
The xmlNode[] respresent an object and I am trying to work out the best way to Deserialize the xmlNode[] in the object? is it to build up a xmlDocument first and the Deserialize ?
感谢
推荐答案
如果您安装了WCF休息初学者工具包预览,有一个绝招:
If you have the WCF Rest Starter Kit preview installed, there's a neat trick:
- 开启的Visual Studio
- 选择您的XML节点的内容(使你的节点之一的XML),并从编辑菜单复制到剪贴板
- 在Visual Studio中,选择粘贴XML作为类型
这将粘贴XML这是在剪贴板到您的项目作为一个C#类,能够反序列化的确切的XML。 !非常漂亮
This will paste your XML that's on the clipboard into your project as a C# class that is capable of deserializing that exact XML. Pretty nifty!
请参阅一下这些博客文章:
See these blog posts about it:
- 的
- 的
- Aaron Skonnard: WCF REST Starter Kit: Paste XML as Types
- "Paste XML as Types" in REST Starter Kit
这应该为你节省大量的输入,使生活变得更加简单。
That should save you a lot of typing and make life a lot easier!
更新:
OK,你已经从你回来的XML生成你的类。现在,你需要一个的XmlNode
转换为类
您将不得不做这样的事情: {
MemoryStream的STM =:; T>(XmlNode的节点),其中T / p>
You'll have to do something like this:
private static T ConvertNode<T>(XmlNode node) where T: class
{
MemoryStream stm = new MemoryStream();
StreamWriter stw = new StreamWriter(stm);
stw.Write(node.OuterXml);
stw.Flush();
stm.Position = 0;
XmlSerializer ser = new XmlSerializer(typeof(T));
T result = (ser.Deserialize(stm) as T);
return result;
}
您需要编写XML表示(财产。 OuterXml
)的的XmlNode
来流(这里的MemoryStream
),然后使用的XmlSerializer
连载回从该流的对象。
You need to write the XML representation (property .OuterXml
) of the XmlNode
to a stream (here a MemoryStream
) and then use the XmlSerializer
to serialize back the object from that stream.
您可以用一般的方法做出来,叫
You can do it with the generic method and call
Customer myCustomer = ConvertNode<Customer>(xmlNode);
或你甚至可以把这些代码插入 XmlNode的任何扩展方法
类,所以你可以写:
or you could even turn that code into either an extension method on the XmlNode
class so you could write:
Customer myCustomer = xmlNode.ConvertNode<Customer>();
马克
Marc
这篇关于的xmlNode对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!