Используя этот класс коллекции и связанные расширения: http://searisen.com/xmllib/xelementcollection.wiki
И эти классы:
public class Project
{
XElement self;
public Project(FileInfo file)
{
self = XElement.Load(file.FullName);
}
public ItemGroup[] ItemGroup
{
get
{
return _ItemGroup
?? (_ItemGroup = self.GetEnumerable("ItemGroup", x => new ItemGroup(x)).ToArray());
}
}
ItemGroup[] _ItemGroup;
}
public class ItemGroup
{
XElement self;
public ItemGroup(XElement self)
{
this.self = self;
}
public XElementCollection Build
{
get
{
return _Build
?? (_Build = new XElementCollection(self, "Build",
(a, b) => a.Get("Include", string.Empty) ==
b.Get("Include", string.Empty),
false));
}
}
XElementCollection _Build;
public XElementCollection NotInBuild
{
get
{
return _NotInBuild
?? (_NotInBuild = new XElementCollection(self, "NotInBuild",
(a, b) => a.Get("Include", string.Empty) ==
b.Get("Include", string.Empty),
false));
}
}
XElementCollection _NotInBuild;
}
Тогда такая грязная реализация:
Project project = new Project(xmlFile2);
XElement find = null;
ItemGroup item = project.ItemGroup.FirstOrDefault(i =>
(find = i.Build.Find(x => x.Get("Include", string.Empty) == "myfile.cs")) != null);
if (null != find)
{
XElement not = new XElement(find.Name.Namespace + "NotInBuild");
not.Set("Include", "myfile.cs", true);
foreach (var child in find.Elements().ToArray())
not.Add(child);
find.Remove();
ItemGroup notGroup = project.ItemGroup.FirstOrDefault(i => i.NotInBuild.Count > 0);
notGroup.NotInBuild.Add(not);
}
При использовании методов расширения, указанных выше, проблема с пространством имен не является проблемой.