2013-03-20 70 views
2

我有一個XML文檔(請參閱下面的摘錄),並且我有一個方法可以在3個字符串參數中傳遞 - 用戶名,文件名和狀態。我需要程序查看XML文檔,將文件名與文件的DMC元素進行匹配,然後將狀態和currentUser元素值更改爲傳遞給我的方法的userName和status值。匹配並選擇XML元素並替換同級元素的值

<dataModule> 
    <DMC>DMC-PO-A-49-00-00-00A-012A-C_001.SGM</DMC> 
    <techName>Pneumatic and shaft power gas turbine engine</techName> 
    <infoName>General warnings and cautions and related safety data</infoName> 
    <status>Checked In</status> 
    <notes>-</notes> 
    <currentUser>-</currentUser> 
</dataModule> 
<dataModule> 
    <DMC>DMC-PO-A-49-00-00-00A-00VA-C_001.SGM</DMC> 
    <techName>Pneumatic and shaft power gas turbine engine</techName> 
    <infoName>List of Applicable Specifications and Documentation</infoName> 
    <status>Checked In</status> 
    <notes>-</notes> 
    <currentUser>-</currentUser> 
</dataModule> 
<dataModule> 
    <DMC>DMC-PO-A-49-00-00-00A-001A-C_001.SGM</DMC> 
    <techName>Pneumatic and shaft power gas turbine engine</techName> 
    <infoName>Title page</infoName> 
    <status>Checked In</status> 
    <notes>-</notes> 
    <currentUser>-</currentUser> 
</dataModule> 

目前我有以下代碼。我希望這可以清楚表明我想要達到的目標。這是一個WinForms項目,我想用Linq來做。

public static void updateStatus(string user, string file, string status) 
{ 
    XDocument doc = XDocument.Load(Form1.CSDBpath + Form1.projectName + "\\Data.xml"); 

    var el = from item in doc.Descendants("dataModule") 
      where item.Descendants("DMC").First().Value == file 
      select item; 

    var stat = el.Descendants("status"); 

    // code here to change the value of the 'status' element text 

    var newUser = el.Descendants("currentUser"); 

    // code here to change the value of the 'currentUser' element text 

} 

回答

0

您可能已經通過的事實,你的LINQ查詢返回一個IEnumerable<XElement>,而不是一個單一的XElement絆倒。這裏有一種方法可以達到你想要的效果:

public static void updateStatus(string user, string file, string status) 
{ 
    XDocument doc = XDocument.Load(@"C:\Projects\ConsoleApp\XMLDocument.xml"); 

    var els = from item in doc.Descendants("dataModule") 
       where item.Descendants("DMC").First().Value == file 
       select item; 

    if (els.Count() > 0) 
    { 
     XElement el = els.First(); 
     el.SetElementValue("status", status); 
     el.SetElementValue("currentUser", user); 

     doc.Save(@"C:\Projects\ConsoleApp\XMLDocument.xml"); 
    } 
} 
+0

非常感謝Jacob,perfect。正是我需要的。 – Daedalus 2013-03-20 16:41:11

+0

我更新了我的代碼,因爲我在一個沒有意義的地方檢查null,所以一定要抓住更新後的版本。 – 2013-03-20 16:47:47