views:

48

answers:

4

Hi guys,

If you like problems to resolve, here a big one :D

First, It isn't about serialization, ok?

Well, my situation... I am writting a function that I will pass as parameter a Xml (XmlDocument) and an object (Object) as reference. It will return to me a object (object that was referenced) filled with the values from the Xml (XmlDocument).

For example:

I have a Xml like:

<user>
  <id>1</id>
  <name>Daniel</name>
</user>

Also I have my function

public Object transformXmlToObject (XmlDocument xml, Object ref)
{
  // Scroll each parameters in Xml and fill the object(ref) using reflection.
  return ref;
}

How will I use it?

I will use like this:

[WebMethod]
public XmlDocument RecebeLoteRPS(XmlDocument xml)
{
  // class user receive the object converted from the function
  User user = new User();
  user = transformXmlToObject(xml, user);

  // object filled 
}

I need help guys, please.

Best regards, Dan

A: 

Erm, yes, this is exactly about serialization. In fact, this is exactly what XML serialization was written for.

Anyway, if you want to write your own, perhaps you can set properties based on the tags in your XML blob? i.e. if you User object has an Id and a Name property, perhaps you should set them in accordance with the XML blob?

Brad Heller
+2  A: 

This should do what you want.

using System.Xml;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System.Collections;

namespace MyProject.Helpers
{
    public class XMLHelper
    {
        public static void HydrateXMLtoObject(object myObject, XmlNode node)
        {
            if (node == null)
            {
                return;
            }

            PropertyInfo propertyInfo;
            IEnumerator list = node.GetEnumerator();
            XmlNode tempNode;

            while (list.MoveNext())
            {
                tempNode = (XmlNode)list.Current;

                propertyInfo = myObject.GetType().GetProperty(tempNode.Name);

                if (propertyInfo != null) {
                    setProperty(myObject,propertyInfo, tempNode.InnerText);

                }
            }
        }
    }
}
andyuk
A: 

I agree, this is indeed about Serialization, and should be what you're looking for. However, to pique your interest about querying XML documents the easy way, have a look at LINQ to XML.

drharris
+1  A: 

If User is an already-defined object with properties to be filled in with the XML data, then yes, this is an XML serialization problem.

If you want User to be an object with dynamic structure based at run-time on the XML data, then take a look at ExpandoObject in .NET 4.0. It should be possible to traverse the XML tree and build an equivalent tree of ExpandoObject instances.

Stephen Cleary