将类型转换为数组

用户名

我正在为Web服务创建一个解析器。我在路障中。

我有一个XML文档

<AdvisorName>
  <PersonNameTitle>String[]</PersonNameTitle>
  <PersonGivenName>String[]</PersonGivenName>
  <PersonFamilyName>String</PersonFamilyName>
  <PersonNameSuffix>String[]</PersonNameSuffix>
  <PersonRequestedName>String</PersonRequestedName>
</AdvisorName>

我的代码是

foreach (XElement childNodeprop in childNodesPropLst)
{
    XElement childElement = childNodeprop.Element(prop.Name);

    if (childElement != null)
    {
        // Error happens at next line:
        prop.SetValue(obj, Convert.ChangeType(childElement.Value, prop.PropertyType), 
            null);

        break;
    }
}

如您所见,返回类型是数组的XML不能转换它。

完整代码附在此处

foreach (var prop in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.SetProperty))
{
    if (!prop.Name.Equals("ExtensionData"))
    { 
        if (prop.PropertyType.IsPrimitive())
        {
            var childNodesPropLst = doc.Descendants(propertyName);
            foreach (XElement childNodeprop in childNodesPropLst)
            {
                XElement childElement = childNodeprop.Element(prop.Name);
                if (childElement != null)
                {
                    prop.SetValue(obj, Convert.ChangeType(childElement.Value, prop.PropertyType), null);
                    break;
                }
            }
        }
    }
}
科林

我同意Rufus的观点,即如果使用.NET的内置XML序列化(XML序列介绍),则可能不需要自定义XML反序列化,但是如果必须的话,可以尝试使用TypeConverters:

var type = //get type
TypeDescriptor.GetConverter(type).ConvertFrom(stringSerialization);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章