我想要更新我的XML文档,但为了做到这一点,首先,我需要获取其中一个节点的id。
<?xml version="1.0" encoding="utf-8"?>
<backupatmail>
(... backups with id 0 & 1)
<backup id="2">
<foldername>Dwa</foldername>
<backupdate>16/10/2015</backupdate>
<comment>comment will be set on UI</comment>
<numberofparts>1</numberofparts>
<lastsucceed></lastsucceed>
</backup>
(... backups with id 3 & 4)
</backupatmail>
我写了这个:
public static int GetSpecificBackupID(XDocument xdoc, string folderName)
{
int lastId = (int)xdoc.Descendants("backup").Where(e => e.Attribute("foldername").Value.Equals(folderName)).Single().Attribute("id");
return lastId;
}
但是我总是得到发生类型'System.NullReferenceException'的未处理异常。
你能指出那个明显的问题吗? ; - )另一件事是(让我们称之为奖金问题):
如何在上面的方法中添加另一个“where”条件?我需要非常确定该ID,所以我也考虑过检查foldername属性。
答案 0 :(得分:4)
foldername
不是属性 - 它是一个元素。这就是你在e.Attribute("foldername").Value
得到NullReferenceException的原因。正确的查询是
int lastId = (int)xdoc.Descendants("backup")
.Where(b => (string)b.Element("foldername") == folderName)
.Single().Attribute("id");
BTW您可以使用重载的Single
运算符并移除Where
:
int id = (int)xdoc.Descendants("backup")
.Single(b => (string)b.Element("foldername") == foldername)
.Attribute("id");