xmlNode to objects

前端 未结 3 1723
借酒劲吻你
借酒劲吻你 2021-02-05 18:14

I have been working with a 3rd party java based REST webservice, that returns an array of xmlNodes.

The xmlNode[] respresent an object and I am trying to work out the b

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-05 19:02

    If you have the WCF Rest Starter Kit preview installed, there's a neat trick:

    • open Visual Studio
    • select your XML node contents (the XML that makes up one of your nodes) and copy it to the clipboard
    • from your "Edit" menu in Visual Studio, pick "Paste XML as Types"

    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!

    UPDATE:
    OK, you already have your classes generated from the XML you get back. Now you need to convert a XmlNode to your class.

    You'll have to do something like this:

    private static T ConvertNode(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;
    }
    

    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(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();
    

    Marc

提交回复
热议问题