2009-03-20 6 views
1

Je travaille sur une application qui analyse un fichier .csproj. Il doit ajouter une valeur supplémentaire à la propriété <NoWarn> si elle existe. Dans le cas où la propriété n'existe pas, je veux que l'application ajoute cette propriété avec sa valeur au nœud parent spécifié. Comment puis-je atteindre cet objectif? J'utilise LINQ-to-XML pour analyser le fichier de projet.Comment puis-je ajouter une nouvelle propriété dans un fichier xml déjà existant?

Répondre

2

Untested, mais est-ce quelque chose comme:

XNamespace ns = @"http://schemas.microsoft.com/developer/msbuild/2003"; 
XDocument doc = XDocument.Load(path); 
var noWarn = (from grp in doc.Descendants(ns + "PropertyGroup") 
     from el in grp.Descendants(ns + "NoWarn") 
     select el).FirstOrDefault(); 
if(noWarn==null) { 
    var grp = doc.Descendants(ns+"PropertyGroup").First(); 
    grp.Add(new XElement(ns+"NoWarn", "1234")); 
} else { 
    noWarn.Value += "; 1234"; 
} 
doc.Save(path); 
+0

J'ai fait quelques légères modifications à cela et il fonctionne parfaitement ... merci pour l'aide :) – Draco

Questions connexes