Nie*_*lsm 7 c# xml linq null-coalescing-operator
当我使用LINQ将XML文件解析为自定义对象时,我试图阻止具有NULL值.
我在Scott Gu的博客上找到了一个很好的解决方案,但由于某些原因它对我的整数不起作用.我想我使用了相同的语法,但似乎我错过了一些东西.哦,由于某种原因,当节点不为空时它可以工作.
下面是我的代码的摘录.
List<GrantAgresso> lsResult = (from g in xml.Element("root").Elements("Elementname")
select new GrantAgresso()
{
Year = (int?)g.Element("yearnode") ?? 0,
Subdomain = (string)g.Element("domainnode") ?? ""
}).ToList();
Run Code Online (Sandbox Code Playgroud)
错误消息是:
输入字符串的格式不正确.
如果有人知道我做错了什么,请帮忙:)
编辑:一块XML(奇怪的名字,但它不是选择)
<Agresso>
<AgressoQE>
<r3dim_value>2012</r3dim_value>
<r0r0r0dim_value>L5</r0r0r0dim_value>
<r7_x0023_province_x0023_69_x0023_V005>0</r7_x0023_province_x0023_69_x0023_V005>
<r7_x0023_postal_code_x0023_68_x0023_V004 />
<r7_x0023_country_x0023_67_x0023_V003>1004</r7_x0023_country_x0023_67_x0023_V003>
<r7_x0023_communitydistrict_x0023_70_x0023_V006>0</r7_x0023_communitydistrict_x0023_70_x0023_V006>
</AgressoQE>
</Agresso>
Run Code Online (Sandbox Code Playgroud)
如果元素不存在、元素为空或包含无法解析为整数的字符串,以下扩展方法将返回 0:
public static int ToInt(this XElement x, string name)
{
int value;
XElement e = x.Element(name);
if (e == null)
return 0;
else if (int.TryParse(e.Value, out value))
return value;
else return 0;
}
Run Code Online (Sandbox Code Playgroud)
你可以这样使用它:
...
Year = g.ToInt("r3dim_value"),
...
Run Code Online (Sandbox Code Playgroud)
或者,如果您准备好考虑反射成本并接受任何值类型的默认值,则可以使用此扩展方法:
public static T Cast<T>(this XElement x, string name) where T : struct
{
XElement e = x.Element(name);
if (e == null)
return default(T);
else
{
Type t = typeof(T);
MethodInfo mi = t.GetMethod("TryParse",
BindingFlags.Public | BindingFlags.Static,
Type.DefaultBinder,
new Type[] { typeof(string),
t.MakeByRefType() },
null);
var paramList = new object[] { e.Value, null };
mi.Invoke(null, paramList);
return (T)paramList[1]; //returns default(T), if couldn't parse
}
}
Run Code Online (Sandbox Code Playgroud)
并使用它:
...
Year = g.Cast<int>("r3dim_value"),
...
Run Code Online (Sandbox Code Playgroud)