如果你想解决问题,这里有个大问题:D
首先,它不是关于序列化的,好吗?
我的情况是..。我正在编写一个函数,它将作为参数传递一个Xml (XmlDocument)和一个对象( object )作为引用。它将向我返回一个对象(被引用的对象),其中填充了XML值(XmlDocument)。
例如:
我有一个像这样的Xml:
<user>
<id>1</id>
<name>Daniel</name>
</user>我也有我的功能
public Object transformXmlToObject (XmlDocument xml, Object ref)
{
// Scroll each parameters in Xml and fill the object(ref) using reflection.
return ref;
}我将如何使用它?
我将像这样使用:
[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
}我需要帮手,谢谢。
致以最好的问候,丹
发布于 2010-07-17 05:39:29
嗯,是的,这就是关于序列化的。事实上,这正是编写XML序列化的目的。
无论如何,如果您想编写自己的代码,也许可以基于XML blob中的标记来设置属性?也就是说,如果你的用户对象有一个Id和一个Name属性,也许你应该根据XML来设置它们?
发布于 2010-07-17 05:45:45
这应该可以做你想要的事情。
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);
}
}
}
}
}发布于 2010-07-17 05:55:59
如果User是一个已经定义好的对象,其属性需要用User数据填充,那么是的,这是一个XML序列化问题。
如果您希望User是一个在运行时基于XML数据具有动态结构的对象,那么可以看看.NET 4.0中的ExpandoObject。应该可以遍历XML树并构建一个等价的ExpandoObject实例树。
https://stackoverflow.com/questions/3268912
复制相似问题