2015-10-16 69 views
0

有我想要更新的XML文檔,但爲了這樣做,首先,我需要獲取其中一個節點的ID。C#:無法從XML中檢索屬性值

<?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' 未處理的異常發生

你能指點我那個明顯的問題嗎? ;-)

的另一件事是(我們稱之爲獎金問題):

如何添加其他「其中」條件上述方法?我需要非常確定這個ID,所以我想過檢查文件夾名稱屬性。

回答

4

foldername不是一個屬性 - 它的一個元素。這就是爲什麼你在這裏得到NullReferenceException e.Attribute("foldername").Value。正確的查詢是

int lastId = (int)xdoc.Descendants("backup") 
    .Where(b => (string)b.Element("foldername") == folderName) 
    .Single().Attribute("id"); 

順便說一句,您可以使用重載Single運營商和刪除Where

int id = (int)xdoc.Descendants("backup") 
     .Single(b => (string)b.Element("foldername") == foldername) 
     .Attribute("id"); 
+0

謝謝!作爲魅力工作!所以我認爲,我需要這樣做:backupatmail - root;備份 - 節點; id(備份) - 屬性;文件夾名稱 - 元素。我是否明白這一點? –

+0

尖括號中的所有內容'' - 這是一個元素。一切都是'blahblahblah =「...」' - 是一個屬性。 –

+0

比我想象的更簡單!再次感謝m8,很棒的支持! –