1

I want to manipulate a xml file. For example I want to add <Compile Include="Program2.cs" /> and delete <Compile Include="clsBlubb.cs" />. I do not know exactly how to get the right Xml Element (ItemGroup) dynamically and how to add or delete an element. It would be grateful if somebody can help me.

Example Xml:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="clsBlubb.cs" />
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
</Project>
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
Heinrich
  • 307
  • 4
  • 12

1 Answers1

3

It's easy to do with Linq to Xml:

var xdoc = XDocument.Load(path_to_xml); // load xml file
var ns = xdoc.Root.GetDefaultNamespace();

// create new Compile element
var compile = new XElement(ns + "Compile", 
                   new XAttribute("Include" ,"Program2.cs"));

// add it to last ItemGroup element
xdoc.Root.Elements(ns + "ItemGroup").Last().Add(compile); 

// remove another Compile element
xdoc.Root.Elements(ns + "ItemGroup")
    .SelectMany(ig => ig.Elements(ns + "Compile"))
    .Where(c => (string)c.Attribute("Include") == "clsBlubb.cs")
    .Remove();

xdoc.Save(path_to_xml); // save changes back to file

Output:

<Project ToolsVersion="12.0" DefaultTargets="Build" 
         xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
    <Compile Include="Program2.cs" />
  </ItemGroup>
</Project>
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459