2011-11-20 48 views
1

我試圖用新值更新我的xml文件時遇到問題。我有一個類Person,它只包含2個字符串,名稱和說明。我填充此列表並將其寫爲XML文件。然後我填充一個新的列表,其中包含許多相同的名稱,但其中一些包含其他列表不包含的描述。我該如何檢查當前XML文件中的名稱是否包含除「沒有說明」之外的值,這是「無」的默認值? xml文件的使用Linq更新XML文件

部分:

<?xml version="1.0" encoding="utf-8"?> 
<Names> 
    <Person ID="2"> 
    <Name>Aaron</Name> 
    <Description>No description</Description> 
    </Person> 
    <Person ID="2"> 
    <Name>Abdi</Name> 
    <Description>No description</Description> 
    </Person> 
</Names> 

這是寫在列表中的XML文件的方法:我該如何檢查,如果這個人的名字

public static void SaveAllNames(List<Person> names) 
{ 
    XDocument data = XDocument.Load(@"xml\boys\Names.xml"); 

    foreach (Person person in names) 
    { 
     XElement newPerson = new XElement("Person", 
           new XElement("Name", person.Name), 
           new XElement("Description", person.Description) 
          ); 

     newPerson.SetAttributeValue("ID", GetNextAvailableID()); 

     data.Element("Names").Add(newPerson); 
    } 
    data.Save(@"xml\boys\Names.xml"); 
} 

在foreach循環是否已經存在,然後檢查描述是否爲「無描述」以外的內容,如果是,則用新信息更新它?

回答

2

我不知道我的理解正確,你想要什麼,但我假設你想只有當名稱已經存在並且說明當前爲No description(您應該更改爲空字符串,BTW)時才更新描述。

你可以把所有的Person s轉換的名字基於Dictionary

var doc = …; 

var persons = doc.Root.Elements() 
         .ToDictionary(x => (string)x.Element("Name"), x => x); 

,然後查詢它:

if (persons.ContainsKey(name)) 
{ 
    var description = persons[name].Element("Description"); 
    if (description.Value == "No description") 
     description.Value = newDescription; 
} 

也就是說,如果你關心性能。如果不這樣做,你不需要做字典:

var person = doc.Root.Elements("Person") 
        .SingleOrDefault(x => (string)x.Element("Name") == name); 

if (person != null) 
{ 
    var description = person.Element("Description"); 
    if (description.Value == "No description") 
     description.Value = newDescription; 
} 
+0

謝謝你,我使用這個版本,只是編輯了一下,以滿足我的需求:) –

0

我想你可以創建一個peoplelist只包含人不在XML。

像↓

 var containlist = (from p in data.Descendants("Name") select p.Value).ToList(); 
     var result = (from p in peoplelist where !containlist.Contains(p.Name) select p).ToList(); 

,這樣,你就沒有必要用你的存在的方法來改變什麼......

剛過稱之爲..

SaveAllNames(result);