2011-04-27 46 views
0

我想將元素添加到與所述條件的XML文件中的XML查詢:LINQ成與其中具有屬性子句(「ID」)值==「1」

like where attribute("id").value=="1" 

在此代碼的where條款無效:

string xmlFilePath = MapPath("Employees.xml"); 
XDocument xmlDoc = XDocument.Load(xmlFilePath); 
try 
{ 
    xmlDoc.Element("employees").Element("employee") 
     .Where(employee => employee.Attribute("id").Value == "2").FirstOrDefault()) 
     .Add(new XElement("city", "welcome")); 

    xmlDoc.Save(xmlFilePath); 
} 
catch (XmlException ex) 
{ 
    //throw new XmlException 
} 
+0

我很抱歉,但我不明白的問題。你能澄清它嗎?謝謝。 – 2011-04-27 12:28:00

回答

0

這可能會更好地工作:

XDocument xmlDoc = XDocument.Load(xmlFilePath); 
try 
{ 
    xmlDoc 
     // get the employees element 
     .Element("employees") 
     // get all the employee elements 
     .Elements("employee") 
     // but filter down to the first one that has id == 2 
     .Where(employee => employee.Attribute("id").Value == "2").FirstOrDefault() 
     // and add a new city element to it 
     .Add(new XElement("city", "welcome")); 
    // save the document 
    xmlDoc.Save("D:\\x.xml"); 
} 
catch (XmlException ex) 
{ 
    //throw new XmlException 
} 
+0

但錯誤是其中原因不是XML文件的一部分....... – 2011-05-03 10:45:28