C# 使用反射将XML转换为对象
如果你喜欢解决问题,这里有一个大问题:D 首先,它不是关于序列化的,好吗 嗯,我的情况。。。我正在编写一个函数,我将作为参数传递一个Xml(XmlDocument)和一个对象(object)作为引用。它将向我返回一个对象(被引用的对象),其中填充了Xml(XmlDocument)中的值 例如: 我有一个类似于:C# 使用反射将XML转换为对象,c#,xml,reflection,C#,Xml,Reflection,如果你喜欢解决问题,这里有一个大问题:D 首先,它不是关于序列化的,好吗 嗯,我的情况。。。我正在编写一个函数,我将作为参数传递一个Xml(XmlDocument)和一个对象(object)作为引用。它将向我返回一个对象(被引用的对象),其中填充了Xml(XmlDocument)中的值 例如: 我有一个类似于: <user> <id>1</id> <name>Daniel</name> </user> 我将如何使用
<user>
<id>1</id>
<name>Daniel</name>
</user>
我将如何使用它
我将这样使用:
[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
}
我需要帮助,伙计们
致以最良好的祝愿,
Dan呃,是的,这正是关于序列化的。事实上,这正是编写XML序列化的目的
无论如何,如果您想编写自己的,也许可以基于XML blob中的标记设置属性?i、 e.如果用户对象有一个
Id
和一个Name
属性,也许您应该根据XML blob设置它们?这应该是您想要的
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);
}
}
}
}
}
我同意,这确实是关于序列化的,应该是您正在寻找的。但是,为了激发您对以简单方式查询XML文档的兴趣,请看一看。如果
User
是一个已定义的对象,其属性将用XML数据填充,那么是的,这是一个XML序列化问题
如果希望
User
成为一个在运行时基于XML数据的动态结构的对象,请查看.NET 4.0中的ExpandoObject
。应该可以遍历XML树并构建一个等价的ExpandoObject
实例树。我将在@andyuk发布的答案中添加一些类型验证。因此,对于每个属性,它将查找属性类型,然后尝试转换xml值,以便不会引发异常
但仍然需要确保xml数据应该具有与插入属性值相同的数据类型。您可以对xml文件使用xsd文件,或者如果您知道您的数据并且它不会更改,则可以忽略它
var pi = entity.GetType( ).GetProperty( eleProperty.Name.LocalName );
if ( pi.PropertyType == typeof( DateTime ) )
{
DateTime val = DateTime.MinValue;
DateTime.TryParse( ele.Value, out val );
pi.SetValue( entity, val, null );
}
else if ( pi.PropertyType == typeof( Int32 ) )
{
int val = 0;
Int32.TryParse( eleProperty.Value, out val );
pi.SetValue( entity, val, null );
}
else if ( pi.PropertyType == typeof( bool ) )
{
bool val = false;
Boolean.TryParse( eleProperty.Value, out val );
pi.SetValue( entity, val, null );
}
else
{
pi.SetValue( entity, eleProperty.Value, null );
}
听起来对我来说是关于序列化的——确切地说是XmlSerializer序列化。但也许不是。这怎么不是序列化呢?
var pi = entity.GetType( ).GetProperty( eleProperty.Name.LocalName );
if ( pi.PropertyType == typeof( DateTime ) )
{
DateTime val = DateTime.MinValue;
DateTime.TryParse( ele.Value, out val );
pi.SetValue( entity, val, null );
}
else if ( pi.PropertyType == typeof( Int32 ) )
{
int val = 0;
Int32.TryParse( eleProperty.Value, out val );
pi.SetValue( entity, val, null );
}
else if ( pi.PropertyType == typeof( bool ) )
{
bool val = false;
Boolean.TryParse( eleProperty.Value, out val );
pi.SetValue( entity, val, null );
}
else
{
pi.SetValue( entity, eleProperty.Value, null );
}