XElement是否支持nil = true
问题描述:
我将以下xml解析到XElement命名条目中。XElement是否支持nil = true
<Person>
<Name>Ann</Name>
<Age i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" />
</Person>
时,取年龄属性我写这篇文章:
var entry =
XElement.Parse(
"<Person><Name>Ann</Name><Age i:nil=\"true\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" /></Person>");
var age = entry.Element("Age").Value;
年龄现在是“”,我不知道是否有某种建立的方式来得到一个空的,而不是“”?
大多数搜索都会讨论如果条目不在xml中,但我总是会像这样填充空值。
答
不,我不相信有什么事,对于这一点,但它会死很容易编写扩展方法:
private static readonly XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
public static string NilAwareValue(this XElement element)
{
XAttribute nil = element.Attribute(ns + "nil");
return nil != null && (bool) nil ? null : element.Value;
}
或者使用可空布尔转换:
public static string NilAwareValue(this XElement element)
{
return (bool?) element.Attribute(ns + "nil") ?? false ? null : element.Value;
}