I want to create a tool that manipulates C# project files
(Basically we want to import targets files at some places in the *.csproj file and otherwise check that the file follows our standards)
What is the best way of doing this? I am planning to use C# and XDocument (LINQ to XML) and manipulated the nodes. But is that the best way? Other alternates may be:
- Find the XSD for csproj/msbuild and create stronly typed objects that represent the project file. is this possible?
- Are there other tools/languages that are better (It could use this as an excuse to learn Ruby). An answer would have to have some links to examples for manipulating XML.
Maybe the real question is: Wh开发者_JS百科at is the best way to read and manipulate XML programatically?
I would personally just use LINQ to XML directly... unless you're doing really heavy processing, I don't think it would be worth creating an object model for it. Just how many rules/whatever do you need for this tool?
MSBuild (which is the format of project files) has an object model that you can use for applications such as this.
We have an in-house tool that manipulates project files on the fly to update references and set various properties. Since project files are not that complicated, we simply manipulate the XML directly. The tool was written long before LINQ was available, so it doesn't use it, but I see no reason why you couldn't do what Jon's suggesting.
When we upgraded from VS2005 to VS2008 we only had to do minor adjustments to the code, but of course there's no guarantees in that regard. We may have to do bigger adjustments for future versions.
If you're interested, there's a bit more info on our tool in my answer to this question Should a .sln be committed to source control?
As per second part of our question how to manipulate XML programatically, here is some xml from a project configuration file. (web.config)
<system.web>
<compilation debug="false">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=1.0.0.0, Culture=neutral,
</compilation>
</compilation>
and to parse using LINQ-TO-XML, something like follows
XDocument assemblies = XDocument.Parse("web.config");
var projectAssemblies= from a in assemblies.Descendants("system.web\assemblies")
select new // What ever object you waant
{
Assembly = a.Attribute("assembly").Value.ToString(),
Version = a.Attribute("Version").Value.ToString(),
Culture = a.Element("Culture").Value.ToString(),
PublicKeyToken = a.Attribute("PublicKeyToken").Value.ToString()
};
foreach (var v in projectAssemblies)
{
// enjoy them
}
hope it helps
精彩评论