我有一个XML文档(参见下面的摘录),我有一个方法,我传递3个字符串参数 - 用户名,文件名和状态。我需要程序查看XML文档,将文件名与文件的DMC元素匹配,然后将status和currentUser元素值更改为我传递给my方法的userName和status值。
<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 :(得分: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");
}
}