Thursday, April 14, 2011

How can I add a new property in an already existing xml file?

Hi,

I am working on an application that parses a .csproj file. It needs to add an additional value to the <NoWarn> property if it exists. In the event that the property does not exist I want the application to add this property with its value to the specified parent node. How can I achieve this? I am using LINQ-to-XML to parse the project file.

From stackoverflow
  • Untested, but is it something like:

    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);
    
    Draco : I made some slight modifications to this and it works perfectly...thanx for the help :)

0 comments:

Post a Comment