Gow*_*nSS 0 .net c# xml xelement linq-to-xml
让我们考虑以下xml文档:
<contact>
<name>Hines</name>
<phone>206-555-0144</phone>
<mobile>425-555-0145</mobile>
</contact>
Run Code Online (Sandbox Code Playgroud)
我从中检索一个值
var value = parent.Element("name").Value;
Run Code Online (Sandbox Code Playgroud)
上面的代码将抛出NullReferenceExceptionif"name"不存在,因为Element将在C#中返回null,但在vb.net中不会返回空值.
所以我的问题是确定何时缺少根节点下的xml节点并获取空值.
您可以创建一个可以轻松重用的扩展方法.将它放在静态类中
public static string ElementValue(this XElement parent, string elementName)
{
var xel = parent.Element(elementName);
return xel == null ? "" : xel.Value;
}
Run Code Online (Sandbox Code Playgroud)
现在你可以这样称呼它
string result = parent.ElementValue("name");
Run Code Online (Sandbox Code Playgroud)
UPDATE
如果null在元素不存在时返回而不是空字符串,则可以区分空元素和缺少元素.
public static string ElementValue(this XElement parent, string elementName)
{
var xel = parent.Element(elementName);
return xel == null ? null : xel.Value;
}
Run Code Online (Sandbox Code Playgroud)
string result = parent.ElementValue("name");
if (result == null) {
Console.WriteLine("Element 'name' is missing!");
} else {
Console.WriteLine("Name = {0}", result);
}
Run Code Online (Sandbox Code Playgroud)
编辑
Microsoft在.NET Framework类库中的不同位置使用以下模式
public static bool TryGetValue(this XElement parent, string elementName,
out string value)
{
var xel = parent.Element(elementName);
if (xel == null) {
value = null;
return false;
}
value = xel.Value;
return true;
}
Run Code Online (Sandbox Code Playgroud)
它可以像这样调用
string result;
if (parent.TryGetValue("name", out result)) {
Console.WriteLine("Name = {0}", result);
}
Run Code Online (Sandbox Code Playgroud)
UPDATE
使用C#6.0(Visual Studio 2015),Microsoft引入了空传播运算符,?.简化了很多事情:
var value = parent.Element("name")?.Value;
Run Code Online (Sandbox Code Playgroud)
即使找不到元素,这也只是将值设置为null.
??如果要返回另一个值,还可以将它与coalesce运算符组合null:
var value = parent.Element("name")?.Value ?? "";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4564 次 |
| 最近记录: |