我正在为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;
}
}
}
}
}
答案 0 :(得分:1)
我同意Rufus的说法,如果使用.NET的内置XML序列化(Introducing XML Serialization),可能不需要自定义XML反序列化,但如果必须,可以尝试使用TypeConverters,如:
var type = //get type
TypeDescriptor.GetConverter(type).ConvertFrom(stringSerialization);
答案 1 :(得分:0)
我想我已经对它做了很多工作
if (prop.PropertyType.IsArray )
{
ArrayList arrLst = new ArrayList();
var arrayElements = childNodeprop.Elements(prop.Name);
foreach(XElement element in arrayElements )
{
arrLst.Add(element.Value);
}
var BaseElementType= prop.PropertyType.GetElementType();
prop.SetValue(obj, arrLst.ToArray(BaseElementType), null);
}
and it works..