2013-06-03 42 views
0

我有一個DataGridView控件,其中一些值被打印。 而且我也有一個xml文件。用戶可以更改DataGridView的警告列中的值,並且需要將其保存在xml文件中。更好的處理XML更新的方法

下面的程序只是做這項工作

XDocument xdoc = XDocument.Load(filePath); 

//match the record 
    foreach (var rule in xdoc.Descendants("Rule")) 
    { 
     foreach (var row in dgRulesMaster.Rows.Cast<DataGridViewRow>()) 
     { 
     if (rule.Attribute("id").Value == row.Cells[0].Value.ToString()) 
      { 
       rule.Attribute("action").Value = row.Cells[3].Value.ToString(); 
      } 
     } 
    } 

//save the record 
xdoc.Save(filePath); 

匹配的網格值與XML文檔和匹配的值,更新所需要的XML屬性。

有沒有更好的方法來編碼?

感謝

+0

是XML文檔1:用的DataGridView 1的關係或者是有沒有ISN的XML文檔中的其他數據在DataGridView中不存在? – David

+0

存在1:1關係 –

+0

那麼我的問題就是爲什麼你需要更新文檔中的一個或多個值?您可以簡單地執行焦土策略,刪除現有的xml文檔並將DataGridView序列化爲XML並將其保存到文件系統。值應該是一樣的否? – David

回答

1

你可以做這樣的事情:

var rules = dgRulesMaster.Rows.Cast<DataGridViewRow>() 
         .Select(x => new { 
            RuleId = x.Cells[0].Value.ToString(), 
            IsWarning = x.Cells[3].Value.ToString() }); 

var tuples = from n in xdoc.Descendants("Rule") 
      from r in rules 
      where n.Attribute("id").Value == r.RuleId 
      select new { Node = n, Rule = r }; 

foreach(var tuple in tuples) 
    tuple.Node.Attribute("action").Value = tuple.Rule.IsWarning; 

這是基本相同的,更多的只是有點LINQ-Y。這是否「更好」是值得商榷的。我刪除的一件事是將IsWarning首先轉換爲字符串,然後轉換爲int,最後再轉換回字符串。它現在被轉換爲一次字符串,並以此方式離開。

+0

'System.Windows.Forms.DataGridViewRowCollection'沒有包含'Select'的定義,也沒有找到接受類型'System.Windows.Forms.DataGridViewRowCollection'的第一個參數的擴展方法'Select' –

+1

使用System添加''。 Linq;'到你的cs文件 –

+0

dgRulesMaster是DataGridView ...它沒有「Select」 –

-1

XPath允許您在xml中使用很多功能來定位節點。使用XPathNavigator修改XML文件的微軟的例子如下:

XmlDocument document = new XmlDocument(); 
document.Load("contosoBooks.xml"); 
XPathNavigator navigator = document.CreateNavigator(); 

XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable); 
manager.AddNamespace("bk", "http://www.contoso.com/books"); 

foreach (XPathNavigator nav in navigator.Select("//bk:price", manager)) 
{ 
    if (nav.Value == "11.99") 
    { 
     nav.SetValue("12.99"); 
    } 
} 

Console.WriteLine(navigator.OuterXml); 

來源:http://msdn.microsoft.com/en-us/library/zx28tfx1(v=vs.80).aspx