我将以下 xml 解析为 XElement 命名条目。
<Person>
<Name>Ann</Name>
<Age i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" />
</Person>
Run Code Online (Sandbox Code Playgroud)
当获取年龄属性时,我这样写:
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;
Run Code Online (Sandbox Code Playgroud)
年龄现在是“”,我想知道是否有某种构建方式可以得到空值而不是“”?
大多数搜索都会讨论条目是否不在 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;
}
Run Code Online (Sandbox Code Playgroud)
或者使用可为 null 的 bool 转换:
public static string NilAwareValue(this XElement element)
{
return (bool?) element.Attribute(ns + "nil") ?? false ? null : element.Value;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1119 次 |
| 最近记录: |