我正在尝试从 C# .csproj 文件添加和删除元素。该文件的部分内容如下所示。有人可以告诉我如何做以下两件事吗?
- 添加一个元素,如下所示(该行显示“我想添加
这”)
- 删除一个元素。例如,假设我想删除 I 行
已在下面指出。
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
</PropertyGroup>
<ItemGroup>
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
</ItemGroup>
<ItemGroup>
<Compile Include="Generate\DatabaseContext.cs" />
<Compile Include="Generate\EntityClasses.cs" />
<Compile Include="Generate\Extensions.cs" />
<Compile Include="Schema\Column.cs" />
<Compile Include="Schema\EntityRef.cs" />
<Compile Include="SerializedData\Tables.xml" /> //I want to add this
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
您可以通过以下方式添加指定的行:
XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
XDocument xDoc = XDocument.Load(fileName);
var b = xDoc.Descendants(ns + "Compile").First();
b.Parent.Add(
new XElement(ns + "Compile",
new XAttribute("Include", @"SerializedData\Tables.xml")
)
);
xDoc.Save(fileName);
要删除指定的行,请尝试以下操作:
XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
XDocument xDoc = XDocument.Load(fileName);
var b = xDoc.Descendants(ns + "Compile")
.Where(el => el.Attribute("Include").Value == @"SerializedData\Tables.xml");
if (b != null)
{
b.Remove();
xDoc.Save(fileName);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)